Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read signed int from bytes in java?

Tags:

java

binary

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.

like image 859
Siva Avatar asked Aug 23 '11 08:08

Siva


People also ask

What is a signed byte in Java?

In Java, byte is an 8-bit signed (positive and negative) data type, values from -128 (-2^7) to 127 (2^7-1) . For unsigned byte , the allowed values are from 0 to 255 . Java doesn't have unsigned bytes (0 to 255).

Can we convert byte to int in Java?

The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int.

Can you cast an int to a byte?

An int value can be converted into bytes by using the method int. to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.

Does Java have signed int?

int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.


1 Answers

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));
like image 111
Peter Lawrey Avatar answered Sep 18 '22 20:09

Peter Lawrey