如何在大端机器(C)上读取 4 字节整数后写入 24 位消息?
-
09-10-2019 - |
题
我正在构建一条消息以通过网络发送 24 位数字。对于小端机器,代码是(ptr是指向消息缓冲区的指针):
*ptr++ = (num >> 16) & 0xFF;
*ptr++ = (num >> 8) & 0xFF;
*ptr++ = (num) & 0xFF;
(因此,如果 num0、num1、num2 和 num3 是组成 num 的各个字节,则消息将被编码为 num2|num1|num0
.)
编码的代码应该是什么 num2|num1|num0
在大端机器上?
解决方案
无论endianess如何,您的代码都是便携式的。换档操作员 >>
<<
使用这些值,而不是代表。
其他提示
这里的问题是,按什么字节顺序 信息 被发送/构造?因为无论您是在一台大型机器上,都不重要 num
, ,因为您已经分裂了 num
以一种终结的方式进入个体字节。
您发布的代码商店24位 num
在Big Endian(又名网络字节订单)中。因此,如果那是您想要的,您已经完成了。如果您想将其存储在Big Little中,只需转换订单:
*ptr++ = (num) & 0xFF;
*ptr++ = (num >> 8) & 0xFF;
*ptr++ = (num >> 16) & 0xFF;
在接收机器中,无论字节序如何,如果您以与 ptr 中存储的顺序相同的顺序接收它们,请像这样组装它们:
num = (ptr[0] << 16) + (ptr[1] << 8) + (ptr[2]);
int main(int argc, char** argv) {
int a, b;
a = 0x0f000000; // Contain 32 bit value
printf("before = %d\n", a);
b = a & (~0xff000000); // convert the last 8 bits to zero so we got only 24 bit value in b
printf("After = %d\n", b);
return (EXIT_SUCCESS);
}
有一个包含32位值的数字,但数字B仅包含24位,从最小的数字开始。这并不取决于尼亚尼斯,因为位运算符不使用内存表示。
所以你可以使用
num = num & (~0xff000000);
要获得最后24位值。
不隶属于 StackOverflow