如何将INT32_T的4个字节写入C中的Big-Endian订单的二进制文件?
我想将int32_t
的4个字节写入大端顺序的二进制文件。我直接使用了fwrite()
和指向我的int32_t
的指针,但它有些可行,但问题是我的整数是用小序列编写的,字节先写。例如,如果我写的话:
int32_t specialInt = 262;
fwrite(&specialInt, 4, 1, myFile);
我会用十六进制编辑器打开它,我会看到:
06 01 00 00 ...
与我想要的方式相比,这是倒退的。我想要:
00 00 01 06 ...
如何使我的int_32t
按大阶订单?是否有一个内置的C库函数可以以正确的顺序获取字节,或者我应该使用memcpy()
将字节放入温度char阵列中,然后一一写入字节向后倒入文件?
I want to write the 4 bytes of an int32_t
to a binary file in big-endian order. I used fwrite()
directly with a pointer to my int32_t
, and it somewhat works, but the problem is that my integer is written in little-endian order, with the smallest bytes written first. For example, if I write:
int32_t specialInt = 262;
fwrite(&specialInt, 4, 1, myFile);
and I open it with my hex editor, I see:
06 01 00 00 ...
which is backwards compared to how I want it. I would like:
00 00 01 06 ...
How should I get my int_32t
to be in big-endian order? Is there a built-in C library function that will get the bytes in the correct order, or should I use memcpy()
to put the bytes into a temp char array, then write the bytes one by one backwards into the file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢PMG在评论中写下答案:
假设
char_bit == 8
:Thanks pmg for writing the answer in the comment:
Assuming
CHAR_BIT == 8
:您可以在POSIX 2001标准中使用
htonl()
函数arpa/inet.h
标题。参见 https://linux.die.net/man/3/ntohl是互联网字节订单,称为“网络字节订单”。
您需要将
int32_t
转换为uint32_t
。该铸件由C标准定义。接下来,它通过htonl()
将其转换为网络endian,然后将其写入文件:可以用复合文字来缩写一点。
You could use
htonl()
function from POSIX 2001 standard available inarpa/inet.h
header. See https://linux.die.net/man/3/ntohlBig endian is Internet byte order, known as "network byte order".
You need to transform
int32_t
touint32_t
. This cast is defined by C standard. Next transform it to network endian viahtonl()
and then write it to a file:It could be abbreviated a bit with a compound literal.