Java byte array contains negative numbers

As a further explanation, assume you have 137 as an unsigned byte. That is represented as:

1000 1001

This binary value, when expressed as a signed two's complement number, turns out to be -119. (-128 + 9)

Any unsigned byte values over 128 will be affected by the difference since the left-most bit is used in this way by the two's complement scheme.


Java doesn't have unsigned bytes; all bytes are treated as signed. That's all.

All that really matters is how you think of the bytes, since you rarely ever actually need to do comparisons on bytes. The only significant difference is that they print out as signed, as you've discovered.

If you like, you can use e.g. Guava's UnsignedBytes utilities to view Java bytes as unsigned, but there's really not much practical difference.


Maybe it has something to do with the fact that Java's byte is signed (range -128 to 127) while C#'s is unsigned (0 to 255) :). The information is the same in binary, it's just interpreted differently.


In Java, byte is a signed value (using two's complement to encode negative values), so what you see it correct if unexpected by most people.

To convert a byte to an unsigned int value, use b & 0xff

Tags:

Java

File Io