11

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?

Eric Fossum
  • 2,395
  • 4
  • 26
  • 50
  • Convert to int and then do the shifting. – Apurv Mar 22 '13 at 00:21
  • It's not really duplicated. The linked question is about 2 bytes to int not unsigned bytes. You can deduce that you have to also mask the first byte from the first answer, but that's not obvious at all. I don't get how they could have mark this answer as duplicated. Is it checked before accepted ? Can we report this ? – BaptisteL Jul 18 '17 at 09:17

2 Answers2

23

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
7

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;
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130