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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With