Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java unsigned byte[2] to int? [duplicate]

All I need to do is convert an unsigned two byte array to an integer. I know, I know, Java doesn't have unsigned data types, but my numbers are in pretend unsigned bytes.

byte[] b = {(byte)0x88, (byte)0xb8}; // aka 35000
int i = (byte)b[0] << 8 | (byte)b[1];

Problem is that doesn't convert properly, because it thinks those are signed bytes... How do I convert it back to an int?

like image 542
Eric Fossum Avatar asked Mar 22 '13 00:03

Eric Fossum


1 Answers

There are no unsigned numbers in Java, bytes or ints or anything else. When the bytes are converted to int prior to being bitshifted, they are sign-extended, i.e. 0x88 => 0xFFFFFF88. You need to mask out what you don't need.

Try this

int i = ((b[0] << 8) & 0x0000ff00) | (b[1] & 0x000000ff);

and you will get 35000.

like image 75
rgettman Avatar answered Sep 28 '22 12:09

rgettman