Why byte b = (byte) 0xFF is equals to integer -1?

okami picture okami · Nov 5, 2009 · Viewed 43.4k times · Source

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?

Answer

cletus picture cletus · Nov 5, 2009

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.