Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java read/write: what am I doing wrong here?

Tags:

java

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
???
like image 422
Lisa Anne Avatar asked Dec 31 '25 23:12

Lisa Anne


2 Answers

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();
like image 162
Eran Avatar answered Jan 02 '26 11:01

Eran


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;
like image 40
Harish Avatar answered Jan 02 '26 12:01

Harish