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
???
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();
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With