开发者

Join MSB and LSB of a 16 bit signed integer (two's complement)

开发者 https://www.devze.com 2023-01-05 14:25 出处:网络
I\'m working with a proprietary protocol that transmits integers as 16 bit two\'s complement in two parts. The LSB is transmitted first followed by the MSB. Is the 开发者_开发百科following code to res

I'm working with a proprietary protocol that transmits integers as 16 bit two's complement in two parts. The LSB is transmitted first followed by the MSB. Is the 开发者_开发百科following code to restore the original value correct?

unsigned char message[BLK_SIZE];
// read LSB to message[0] and MSB to message[1]
short my_int = (message[1] << 8) | message[0];


I believe that code will fail if short is not 16 bits, so your code may fail on some platforms. You may never find a platform it fails on though.

int16_t, if available on your target platform(s), may be a better choice.


Your code looks correct, but you could use intrinsic C functions for ensuring that your protocol is truly platform independant:

short my_int = ntohs(*(short*)message)

0

精彩评论

暂无评论...
验证码 换一张
取 消