2 bytes to short java

后端 未结 5 1666
迷失自我
迷失自我 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 03:56

    This happens when trying to concatenate bytes (very subtle)

    byte b1 = (byte) 0xAD;
    byte b2 = (byte) 0xCA;
    short s = (short) (b1<<8 | b2);
    

    The above produces 0xFFCA, which is wrong. This is because b2 is negative (byte type is signed!), which means that when it will get converted to int type for the bit-wise | operation, it will be left-padded with 0xF!

    Therefore, you must remember to mask-out the padded bytes so that they will definitely be zero:

    short s = (short) (b1<<8 | b2 & 0xFF);
    

提交回复
热议问题