What is the best way to work around the fact that ALL Java bytes are signed?

Max picture Max · Aug 14, 2008 · Viewed 26.4k times · Source

In Java, there is no such thing as an unsigned byte.

Working with some low level code, occasionally you need to work with bytes that have unsigned values greater than 128, which causes Java to interpret them as a negative number due to the MSB being used for sign.

What's a good way to work around this? (Saying don't use Java is not an option)

Answer

ejack picture ejack · Aug 21, 2008

It is actually possible to get rid of the if statement and the addition if you do it like this.

byte[] foobar = ..;
int value = (foobar[10] & 0xff);

This way Java doesn't interpret the byte as a negative number and flip the sign bit on the integer also.