posted 8 years ago

So with the data stream (serial port) I am working with I get two bytes for int and the value is signed (Temperature).

I have tried two different methods (which I think I understand but not fully) to convert these to the correct value with some partial success. Meaning one algorithm does not handle the negative numbers and other does not seem to handle positive numbers very well (or I am doing something wrong.)

Output for the 43.3 value:

If I use the -81 , byte array, temp1 is -81 (which is expected) but temp2 is 65456. These are in tenths but I have done the division.

Any guidance on where I have gone wrong?

Thanks

Mike

I have tried two different methods (which I think I understand but not fully) to convert these to the correct value with some partial success. Meaning one algorithm does not handle the negative numbers and other does not seem to handle positive numbers very well (or I am doing something wrong.)

Output for the 43.3 value:

If I use the -81 , byte array, temp1 is -81 (which is expected) but temp2 is 65456. These are in tenths but I have done the division.

Any guidance on where I have gone wrong?

Thanks

Mike

Mike Bates

Ranch Hand

Posts: 81

posted 8 years ago

David,

Thanks for the pointer. Wow, twos-compliment. Google and search on Java Ranch are your friends.

Anyway I found some code, here on JavaRanch,

http://www.coderanch.com/t/406929/Beginning-Java/java/Convert-negative-integer-byte-back#1788511

still trying to understand it, as well as twos-compliment.

It does handle positive and negative numbers. I am trying to figure out if I need to subtract one at the end or is the negative number the number. The code I have above gave -81 but this code gives -80. I also had to deal with endian issues as well.

Still so much to learn.

Regards,

Mike

Thanks for the pointer. Wow, twos-compliment. Google and search on Java Ranch are your friends.

Anyway I found some code, here on JavaRanch,

http://www.coderanch.com/t/406929/Beginning-Java/java/Convert-negative-integer-byte-back#1788511

still trying to understand it, as well as twos-compliment.

It does handle positive and negative numbers. I am trying to figure out if I need to subtract one at the end or is the negative number the number. The code I have above gave -81 but this code gives -80. I also had to deal with endian issues as well.

Still so much to learn.

Regards,

Mike