如何在大端机器(C)上读取 4 字节整数后写入 24 位消息?
我正在构建一条消息以通过网络发送 24 位数字。 对于小端机器,代码是(ptr 是指向消息缓冲区的指针):(
*ptr++ = (num >> 16) & 0xFF;
*ptr++ = (num >> 8) & 0xFF;
*ptr++ = (num) & 0xFF;
因此,如果 num0、num1、num2 和 num3 是组成 num 的各个字节,则消息将被编码为 num2|num1| num0
。)
在大端机器上编码 num2|num1|num0
的代码应该是什么?
I am constructing a message to send a 24-bit number over the network.
For little endian machines, the code is (ptr is the pointer to the message buffer):
*ptr++ = (num >> 16) & 0xFF;
*ptr++ = (num >> 8) & 0xFF;
*ptr++ = (num) & 0xFF;
(So if num0, num1, num2 and num3 are the individual bytes making up num, the message would be encoded as num2|num1|num0
.)
What should be the code for encoding num2|num1|num0
on a big endian machine?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这里的问题是,消息应以什么字节顺序发送/构造?因为无论您使用的是小端还是大端机器,对于
num
来说并不重要,因为您已经以与端序无关的方式将num
划分为各个字节。您发布的代码以大尾数法(也称为网络字节顺序)存储 24 位
num
。所以,如果这就是您想要的,那么您已经完成了。如果您想将其存储在 big little 中,只需颠倒顺序即可:The question here is, in what byte order shall the message be sent/constructed ? Because whether you are on a little or big endian machine doesn't matter with respect to
num
, as you're already dividingnum
into individual bytes in an endian-agnostic way.The code you've posted stores 24 bits of
num
in big endian (aka network byte order). So if that's what you want you're already done. If you want to store it in big little instead, just reverse the order:无论字节顺序如何,您的代码都是可移植的。移位运算符
>>
<<
处理的是值,而不是表示。Your code is portable regardless of endianess. The shift operators
>>
<<
work with the values, not with the representation.在接收机器中,无论字节序如何,如果您以与 ptr 中存储的顺序相同的顺序接收它们,请像这样组装它们:
In the receiving machine, regardless of endian-ness, if you receive them in same order as they are stored in ptr, assemble them like this:
有一个数字包含 32 位值,但数字 b 仅包含 24 位(从最低有效数字开始)。这不依赖于字节顺序,因为按位运算符不适用于内存表示。
所以你可以用它
来获取最后的24位值。
There is a number containing a 32-bit value but number b contains only 24 bits, starting from least significant digit. And that doesn't depend on endianness because bitwise operators don't work with memory representation.
So you can use
to get the last 24-bit value.