2 bytes to short java

后端 未结 5 1650
迷失自我
迷失自我 2020-11-29 03:40

i\'m reading 133 length packet from serialport,last 2 bytes contain CRC values,2 bytes value i\'ve make single(short i think) using java. this what i have done,



        
5条回答
  •  迷失自我
    2020-11-29 04:02

    When converting byte values from a stream into numeric values in Java you have to be very careful with sign extension. There is a trap with negative numbers (values from (unsigned) 128-255).

    Try this (it works if hi and lo are any Java integer type) :

    short val=(short)(((hi & 0xFF) << 8) | (lo & 0xFF));
    

    I find it's best to be explicit with the parentheses in these cases.

提交回复
热议问题