How to read negative byte values in Java less than -128

rohini picture rohini · Apr 27, 2009 · Viewed 10.1k times · Source

I'm reading data from another system using the serial port. I'm reading packets of 133 bytes. The second byte is the packet number and the third byte is the negative value of the packet number.

The problem is that the type byte has a range of -128 to 127. When I attempt to read -129 (outside the range of byte) it will give the value as 127.

What should I do so I can get -129?

Answer

Peter Lawrey picture Peter Lawrey · Apr 27, 2009

You have to determine what range you expect byte values to have. if you expect the range -129 to 126 for example you can use.

int min = 129;
int i = ((b + min) & 0xFF) - min;

BTW You cannot have more than 256 value.