Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 278
Max Avatar asked Aug 14 '08 14:08

Max


People also ask

Are bytes signed in Java?

In Java, byte is an 8-bit signed (positive and negative) data type, values from -128 (-2^7) to 127 (2^7-1) . For unsigned byte , the allowed values are from 0 to 255 . Java doesn't have unsigned bytes (0 to 255).

How are bytes represented in Java?

The eight primitive data types supported by the Java programming language are: byte: The byte data type is an 8-bit signed two's complement integer.

How do you assign bytes in Java?

If you're trying to assign hard-coded values, you can use: byte[] bytes = { (byte) 204, 29, (byte) 207, (byte) 217 }; Note the cast because Java bytes are signed - the cast here will basically force the overflow to a negative value, which is probably what you want.

Why byte is used in Java?

byte. Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.


1 Answers

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.

like image 50
ejack Avatar answered Oct 25 '22 14:10

ejack