views:

1712

answers:

4

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?

+5  A: 

You are getting 127 because a byte is only 8 bits and so the value is wrapping around. -129 won't fit in a java byte. You will have to modify your program to use shorts at the least if you want to fit -129 in a given variable.

Paul Wicks
CaptainAwesomePants
+5  A: 

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.

Peter Lawrey
+2  A: 

I have to guess here a little as I don't know the protocol.

Maybe boths values should be treated as unsigned (positive) bytes in the protocol, they you can convert them to ints later.

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

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

Is it related to this Us Pat 6313763 ? But as the length of the packet is fixed, I don't get it.

It is not possible to store "bigger" numbers than the range 256 in a byte. Maybe you misunderstood the protocol, and its the high and low bits of an int stored in two bytes?

KarlP
A: 

Values less than -128 dont fit into a signed byte. You need to read a short etc.

mP