简体   繁体   中英

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

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.

您的代码看起来正确,但是您可以使用固有的C函数来确保您的协议真正独立于平台:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM