Why byte b = (byte) 0xFF
is equal to integer
-1
?
Ex:
int value = byte b = (byte) 0xFF; System.out.println(value);
it will print -1
?
Representing 0xff With Different Data Types int x = 0xff; assertEquals(255, x); However, if we define a byte variable with the value 0xff, since Java represents a byte using 8 bits and because a byte is a signed data type, the value of 0xff is -1: byte y = (byte) 0xff; assertEquals(-1, y);
So, for example, binary 10000010 represents decimal 130 (128+2) if it's unsigned, but -126 (-128+2) if that same value is signed. Negative one is 0xff, since 64+32+16+8+4+2+1==127.
0xff means "the hexadecimal number ff " - in other words, the integer 255 , which has the binary representation 00000000000000000000000011111111 (when using 32-bit integers). The & operator performs a bitwise AND operation.
This is because we have to represent the number 0, so inclusively 0-127 is the other 128 possibilities of our range. If we were only allowing positive values, such as an unsigned byte where negative numbers aren't possible, the range would be 0-255, since these are 256 different values (including the 0).
Bytes are signed in Java. In binary 0x00 is 0, 0x01 is 1 and so on but all 1s (ie 0xFF) is -1, 0xFE is -2 and so on. See Two's complement, which is the binary encoding mechanism used.
b
is promoted to an int
in determining which overload of system.out.println
to call.
All bytes in Java are signed.
The signed byte 0xff
represents the value -1
. This is because Java uses two's complement to represent signed values. The signed byte 0xff
represents -1
because its most significant bit is 1
(so therefore it represents a negative value) and its value is -128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = -1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With