Search code examples
javaintegerhexunsignedsigned

Converting 0xFF gives me -1 -> Signed vs Unsigned?


Here is my code:

byte b = (byte) 0xFF;
System.out.println(b);

I expect to see 255, but instead I see -1. What's happening? Is the compiler using a signed instead of an unsigned byte?


Solution

  • Maybe you are confused about the difference between storage and representation.

    As the others told you, Java only uses signed integral types. As a byte is only 8 bit, this means you have a range from -128 to 127. But keep in mind: This is only a decimal representation that does not tell you about the binary storage!

    A better reminder for the range of Java's byte type would be the following (decimal) representation:

    0 1 ... 126 127 -128 -127 ... -2 -1
    

    This directly corresponds to the following binary representation:

    00000000 00000001 ... 11111110 11111111
    

    The signed decimal representation is called the two's complement. As you can see, the binary value 11111111, which is exactly 0xFF, corresponds to the (signed) decimal value -1.

    If you now send this value via a stream, you will get the full 0xFF value, regardless what you see in a Java program's console output.