Question

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?

Was it helpful?

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.

OTHER TIPS

In Java type byte is signed, it is not possible to use an "unsigned byte" in java. A workaround would be to use short types

Everytime you operate on a byte variable in Java, (byte) 0xFF is going to be implicitly converted to (int) 0xFFFFFF (i.e. -1). You can do 0xFFFFFF & 0xFF and then you'll get (int) 255 as you wish (you will never be able to get (byte) 255, only (int) 255).

If you only need to store bytes, it doesn't matter how 0xFF is printed on the screen, it's still (byte) 0xFF internally. If you need to operate on them (comparing to an int, adding, subtracting, converting to a string, printing on the screen, and basically anything else), then you need to be aware that they'll get converted to int 0xFFFFFF which is interpreted -1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top