How do I split an integer into 2 byte binary?
Solution 1:
Using simple bitwise operations:
data[0] = (byte) (width & 0xFF);
data[1] = (byte) ((width >> 8) & 0xFF);
How it works:
-
& 0xFF
masks all but the lowest eight bits. -
>> 8
discards the lowest 8 bits by moving all bits 8 places to the right. - The cast to byte is necessary because these bitwise operations work on an
int
and return anint
, which is a bigger data type thanbyte
. The case is safe, since all non-zero bits will fit in thebyte
. For more information, see Conversions and Promotions.
Edit: Taylor L correctly remarks that though >>
works in this case, it may yield incorrect results if you generalize this code to four bytes (since in Java an int
is 32 bits). In that case, it's better to use >>>
instead of >>
. For more information, see the Java tutorial on Bitwise and Bit Shift Operators.
Solution 2:
For converting two bytes the cleanest solution is
data[0] = (byte) width;
data[1] = (byte) (width >>> 8);
For converting an integer to four bytes the code would be
data[0] = (byte) width;
data[1] = (byte) (width >>> 8);
data[2] = (byte) (width >>> 16);
data[3] = (byte) (width >>> 24);
It doesn't matter whether >> or >>> is used for shifting, any one bits created by sign extension will not end up in the resulting bytes.
See also this answer.