Siva Siva - 4 months ago 29
Java Question

how to read signed int from bytes in java?

I have a spec which reads the next two bytes are signed int.

To read that in java i have the following

When i read a signed int in java using the following code i get a value of 65449

Logic for calculation of unsigned

int a =(byte[1] & 0xff) <<8

int b =(byte[0] & 0xff) <<0

int c = a+b


I believe this is wrong because if i and with 0xff i get an unsigned equivalent

so i removed the & 0xff and the logic as given below

int a = byte[1] <<8
int b = byte[0] << 0
int c = a+b
which gives me the value -343
byte[1] =-1
byte[0]=-87


I tried to offset these values with the way the spec reads but this looks wrong.Since the size of the heap doesnt fall under this.

Which is the right way to do for signed int calculation in java?

Here is how the spec goes

somespec() { xtype 8 uint8 xStyle 16 int16 }

xStyle :A signed integer that represents an offset (in bytes) from the start of this Widget() structure to the start of an xStyle() structure that expresses inherited styles for defined by page widget as well as styles that apply specifically to this widget.

Answer

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));