Adverts

Converting a byte to another Java type such as an int or a short is not quite as easy as you might think.

byte b = 127;
int cast = (int)b; //cast has value of 127

b = -128;
cast =
(int)b; //cast has value of -128 we wanted 128

b = -1;
cast =
(int)b; //cast has value of -1 we wanted 255

You will end up with negative values for any byte values greater than 127. This is because Java treats all primitive types as signed values. Often when dealing with bytes, however, you want to treat the values as unsigned (this is very common if you are dealing with image data for instance).

To treat the value as unsigned you need to mask the sign bit like this:

byte b = 127;
int cast = (int)b & 0xff; //cast has value of 127

b = -128;
cast =
(int)b & 0xff; //cast has value of 128

b = -1;
cast =
(int)b & 0xff; //cast has value 255

This operation is very fast so there is little overhead in converting huge chunks of byte data. If you want to convert the bytes to other primitive types, such as shorts, you will need to cast the result of the mask. Example code is shown below.

package example;

public class ByteToInt {

   
public static void main(String[] args) {
       
byte[] b = new byte[] { 127, -128, -1 };
       
for (int i = 0, n = b.length; i < n; i++) {
           
short read = (short) ((short) b[i] & 0xff);
            System.out.println
("Read: " + read);
       
}
    }
}

Adverts

Donate and Help

Please support this site and
Bandwidth doesn't grow on trees y' know :o)

Adverts

Get Adsense