Introduce int as 2 bytes in Java

I need to represent the value 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 a byte in Java can contain values โ€‹โ€‹0-255. Therefore, I expect the first element of the array to have a value of 255, and the second element to be zero. But I get instead -1 and 0. What am I doing wrong? What does this -1 mean?

+6
source share
1 answer

Byte in java from -128 to 127 , not from 0 to 255

-1 1111 1111 in two binary additions , equal to 255 in unsigned byte.

You are not doing anything wrong, you just need to know that if you see -1 , it means that the byte represents bit 1111 1111 .

+10
source

All Articles