Home » Android » java – Negative Int value from Big Endian to Small-Exceptionshub

java – Negative Int value from Big Endian to Small-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

As soon as the byte order in Big and Small Endians is reverse,
then how to manage situation with negative value?
There is a value 130
In Big Endian bytes order it is

(byte)0 (byte)0 (byte)0 (byte)130

The last byte in binary format is looking as 10000010

In reverse order, during conversion to Small Endian,

(byte)130 (byte)0 (byte)0 (byte)0

this byte is the first, and by default in Java, because of first bit in 10000010 = 1

is (the position of value’ sign)

it is translated as signed 2's complement value = -126

How to manage such situation and get the correct value = 130?

I need to pass Integer value from Windows to Android Sockets.

When I pass 130, then the buffer is [0, 0, 0, 130] because in Big Endian the sign is the first bit, and it is 0.

In reverse order 130 = 10000010, 0, 0, 0 and the first 1 is already interpreted as the sign ‘-‘ and I get it as -126 in such simple code:

> public static int ToInt32(byte[] buffer, int pos){
>     int value;
>     value = (byte)buffer[pos]<<24;
>     value = (byte)buffer[pos]<<16;
>     value = (byte)buffer[pos]<<8;
>     value = (byte)buffer[pos];
>     return value; }
How to&Answers: