Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

More byte array to int questions  RSS feed

 
Mike Bates
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Twos-complement.
 
Mike Bates
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!