how to read signed int from bytes in java?

If you value is a signed 16-bit you want a short and int is 32-bit which can also hold the same values but not so naturally.

It appears you wants a signed little endian 16-bit value.

byte[] bytes = 
short s = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).getShort();

or

short s = (short) ((bytes[0] & 0xff) | (bytes[1] << 8));

BTW: You can use an int but its not so simple.

// to get a sign extension.
int i = ((bytes[0] & 0xff) | (bytes[1] << 8)) << 16 >> 16;

or

int i = (bytes[0] & 0xff) | (short) (bytes[1] << 8));

Assuming that bytes[1] is the MSB, and bytes[0] is the LSB, and that you want the answer to be a 16 bit signed integer:

short res16 = ((bytes[1] << 8) | bytes[0]);

Then to get a 32 bit signed integer:

int res32 = res16;  // sign extends.

By the way, the specification should say which of the two bytes is the MSB, and which is the LSB. If it doesn't and if there aren't any examples, you can't implement it!


Somewhere in the spec it will say how an "int16" is represented. Paste THAT part. Or paste a link to the spec so that we can read it ourselves.


I can't compile it right now, but I would do (assuming byte1 and byte0 are realling of byte type).

 int result = byte1;
 result = result << 8;
 result = result | byte0;  //(binary OR)
 if (result & 0x8000 == 0x8000) { //sign extension
   result = result | 0xFFFF0000;
 }

if byte1 and byte0 are ints, you will need to make the `&0xFF

UPDATE because Java forces the expression of an if to be a boolean

Tags:

Java

Binary