Java unsigned byte[2] to int?

12,223

Solution 1

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.

Solution 2

You can use

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

or

int i = ByteBuffer.wrap(b).getChar();

or

int i = ByteBuffer.wrap(b).getShort() & 0xFFFF;
Share:
12,223
Eric Fossum
Author by

Eric Fossum

Studied at WSU now a Software Engineer at SEL Go Cougs!

Updated on June 11, 2022

Comments

  • Eric Fossum
    Eric Fossum almost 2 years

    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?