将 UINT32 值转换为 UINT8 数组[4]
我的问题是如何将 UINT32 值转换为 UINT8 数组[4] (C/C++),最好以独立于字节序的方式?此外,您将如何从 UINT8 数组 [4] 重建 UINT32 值,以返回到开始的位置?
My question is how do you convert a UINT32 value to a UINT8 array[4] (C/C++) preferably in a manner independent of endianness? Additionally, how would you reconstruct the UINT32 value from the UINT8 array[4], to get back to where you started?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您还没有真正说出独立于字节序的含义 - 目前还不清楚,因为字节数组必须具有一些字节序。也就是说,以下其中一个必须满足您的要求:
给定
UINT32 v
和UINT8 a[4]
:“Host” 字节序
(使用机器的本机字节顺序):
或:
或:
大端序
(又名“网络顺序”):
小端序
You haven't really said what you mean by independent of endianness - it's unclear since the byte array must have some endianness. That said, one of the below must answer your requirements:
Given
UINT32 v
andUINT8 a[4]
:"Host" endian
(use the machine's native byte order):
or:
or:
Big endian
(aka "network order"):
Little endian
例如这样:
编辑: 添加括号(>> 似乎比 & 具有更高的优先级)
E.g. like this:
Edit: added parenthesis (>> seems to have higher precedence than &)
如果您不想自己编码,可以使用C库函数htonl() 将 32 位 int 转换为网络字节顺序。还有函数 ntohl() 将它们转换回主机顺序。
一旦它们处于网络字节顺序,只需将 int/long 作为字节数组进行访问即可。
总而言之,这可能是实现您的目标的最便携且经过测试的方式。
If you don't want to code it yourself, you can use the C library function htonl() to convert the 32-bit int to network byte order. There is also the function ntohl() to convert them back to host order.
Once they're in network byte order, it's simply a matter of accessing the int/long as a byte array.
All in all that's are probably the most portable and tested way of achieving your goal.
也可以用指针来做到这一点。 (这是小端字节序,但如果您使用相同的重构方法,那就没有关系)
这会将 uint32 的值分配给 uint8 内存地址之后的 4 个字节,这正是您所需要的。
走另一条路:
One could also do it with pointers. (This is little endian, but if you use the same reconstruction method it won't matter)
This assigns the value of the uint32 to the 4 bytes after the memory address of the uint8, doing exactly what you need.
To go the other way:
使用由 4 个 uint8 数组组成的 Union
和一个 uint32。
所以它按c固有指针Magic自动排序(数组是指向数组开头的指针)
use a Union consisting of an Array with 4 time uint8
and an uint32.
So it sorts automatically by c inherent pointer Magic (Arrays are pointers to start of array)