I need to represent a value of 0xFF00 as two bytes (in Java). I am trying to do it like this:
int val = 0xFF00;
bytearray[0] = (byte)((val >> 8) & 0xFF);
bytearray[1] = (byte)((val >> 0) & 0xFF);
I know that byte in Java can hold values 0-255. So I expect the first array element to have a value of 255 and the second element to be zero. But what I am getting instead is -1 and 0. What I am doing wrong? What this -1 value mean?
Byte in java is from
-128to127, not from0to255-1is1111 1111in two’s complement binary, equal to255in unsigned byte.You aren’t doing anything wrong, you just need to know that if you see
-1, it means the byte is representing the bits1111 1111.