Often we're faced with the need to represent primitive data types as readable/writable bytes that can be sent through a data stream. In Java, there are classes such as DataOutputStream/DataInputStream that can do the work for us, but often a programmer wants to manage the conversions himself (or herself, to be politically correct).
So, how does one convert primitive data types to and from [binary] byte arrays? The answer is this: by working with Binary Bitwise Operators.
Here are some methods used to convert primitive types, and arrays of primitive types, to and from byte arrays.
Order of primitive types in this snippet:
- byte, byte
- short, short
- char, char
- int, int
- long, long
- float, float
- double, double
- boolean, boolean (special)
- String, String (special)
I know there are a few formatting mistakes in the code, but hopefully the syntax is all optimal. Perhaps, perhaps not. Something tells me the String conversion isn't UFT safe, too. Any thoughts? ;)