Reputation: 4595
This is my code snippet:
byte value = (byte) rand.nextInt();
TX.write(value);
int read = RX.read() & 0xFF;
The hardware I am connected gives me back on RX what I write on TX. That works OK as long as I am writing positive numbers, BUT if I write a negative number what i get back does not match with what I wrote....
Please what am I missing?
EDIT: example output
Write: 66
Read: 66
OK AS EXPECTED
Write: -44
Read: 212
???
Write: -121
Read: 135
Write: -51
Read: 205
???
Write: -4
Read: 252
???
Upvotes: 3
Views: 119
Reputation: 5077
It's because 0xFF
is by default an int which is 32 bits. Take -51 for example. In binary it is represented using 2's complement:
You are doing this:
11001101
& 00000000 00000000 00000000 FFFFFFFF
which gives
00000000 00000000 00000000 11001101
= 205
What you want is
11001101
& FFFFFFFF
so you should do
((byte) RX.read()) & ((byte) 0xFF)
See example:
public static void main(String[] args) {
int negative = -51;
System.out.println((int) (negative & (byte) 0xFF)); // = -51
System.out.println((int) (negative & 0xFF)); // = 205
}
Upvotes: 1
Reputation: 1742
It seems that casting int
to byte
will represent the int
as a signed int
using two's complement (for one byte the range would be [10000000
] -128 to 127 [01111111
]; note that -1
is 11111111
and 0
is 00000000
). However RX.read()
treats the byte
as an unsigned int
(range from 0 [00000000
] to 255 [11111111
]).
If you only use one byte you can use:
int r = RX.read() & 0xFF
int read = -(255 - r) if r > 128 else r
Upvotes: 1
Reputation: 269
The BYTE is of 8bit out of which 1 is reserved for sign so max its range is from -128 to 127 so when you to the & 0xFF with the negative sign you will get the unsigned value of the range. hence when u r doing -4 it is giving 252 if u do the -1 then it will give 255 and so on.
Also in your code you can simple use int casting as it works at my end.. example:-
byte b = -14;
int i = (int)b;
Upvotes: 1
Reputation: 393996
If you write a negative byte and then you read it and assign it into an int using RX.read() & 0xFF
, you will get a positive number, since the sign bit of the int will be 0.
Try
int read = RX.read();
Upvotes: 2