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

I am reading data from another system using the serial port. I read 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 bytehas a range from -128 to 127. When I try to read -129 (outside the byte range), it will give a value as 127.

What can I do, can I get -129?

+5
source share
4 answers

You must determine what range you expect from the byte values. if you expect a range of -129 to 126, for example, you can use.

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

BTW You cannot have more than 256 values.

+8

127, 8 , . -129 java-. , , -129 .

+6

, .

, () , ints .

// 0-255
int plus = (int)(plusByte & 0xFF);

// -255 - 0
int minus = 0 - (int)(minusByte & 0xFF);

Us Pat 6313763? , .

"" , 256 . , , int ?

+4

-128 . ..

+1

All Articles