【发布时间】:2017-09-12 00:28:30
【问题描述】:
我通过网络数据包接收一个短整数,这意味着它将以网络字节顺序(大端)的 2 个字节出现。
我想在我的机器上将收到的两个字节组合成一个短 int 变量,它是 little endian 字节顺序。
例子:
short int test = 400; //0x190 in big endian, 0x9001 in little endian
char testResponse[2] = {0x01, 0x90};
//here is my attempt
short int result = testResponse[1] << 8 | testResponse[0];
printf("%d\n", result); //-28671 when expecting 400
任何帮助将不胜感激!
【问题讨论】:
-
你有什么问题?
-
组合这两个数字的方法似乎是比 OR 左移 8 位,但这似乎没有给出正确的结果,所以我想知道是否有人知道我的位算术是错误的。
-
C 中没有“8 位左移”。如果有,
8的移位计数将调用未定义的行为。您最有可能受到整数促销,了解它们!并使用固定宽度的无符号类型。char不保证是无符号的,也不保证有 8 位。根据您对现已删除的答案的评论:我们需要所有相关信息。或者你得到正确的代码,就像我说的那样。 -
字节序是字节在内存中的存储方式,而不是计算值的方式。要获得
0x0190,您需要0x01 << 8 + 0x90。 -
@JeremyRobertson 你得到
short int result = testResponse[0] << 8 | testResponse[1]; printf("%d\n", result);的预期答案了吗(交换了索引)?
标签: c network-programming int hex bit-shift