连接 16 位有符号整数的 MSB 和 LSB(二进制补码)
我正在使用一种专有协议,该协议将整数作为 16 位二进制补码分两部分传输。首先传输 LSB,然后传输 MSB。下面恢复原始值的代码是否正确?
unsigned char message[BLK_SIZE];
// read LSB to message[0] and MSB to message[1]
short my_int = (message[1] << 8) | message[0];
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信如果
short
不是 16 位,代码将会失败,因此您的代码在某些平台上可能会失败。但你可能永远找不到一个失败的平台。int16_t(如果您的目标平台上可用)可能是更好的选择。
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)
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)