【发布时间】:2018-10-23 11:17:45
【问题描述】:
我正在努力解决一个问题,该问题需要我对使用函数 fopen() 创建的目标文件执行十六进制转储。
我已经声明了必要的整数变量(十六进制),如下所示:
//Declare variables
int code = 0xCADE;
输出必须是大字节序,所以我以这种方式交换了字节:
//Swap bytes
int swapped = (code>>8) | (code<<8);
然后我以这种方式打开文件进行二进制输出:
//Open file for binary writing
FILE *dest_file = fopen(filename, "wb");
之后,我使用 fwrite() 以下列方式将变量代码(对应于 16 位字)写入文件:
//Write out first word of header (0xCADE) to file
fwrite(&swapped, sizeof(int), 1, dest_file);
在已写入内容的文件上编译、运行和执行 hexdump 后,我观察到以下输出:
0000000 ca de ca 00
0000004
在额外的“ca 00”之前,基本上一切都是正确的。我不确定为什么会存在并且需要将其删除,以便我的输出只是:
0000000 ca de
0000004
我知道字节顺序问题已在堆栈中得到广泛解决,但在执行搜索后,我不清楚如何对该问题进行分类。我该如何解决这个问题,以便删除“ca 00”?
非常感谢。
编辑:
我都改变了:
//Declare variables
int code = 0xCADE;
//Swap bytes
int swapped = (code>>8) | (code<<8);
到:
//Declare variables
unsigned short int code = 0xCADE;
//Swap bytes
unsigned short int swapped = (code>>8) | (code<<8);
我观察到:
0000000 ca de 00 00
0000004
这让我更接近我需要的东西,但仍然有额外的“00 00”。任何帮助表示赞赏!
【问题讨论】:
-
请发minimal reproducible example,这更像是一个代码难题。
-
如果您只想在文件中存储 2 个字节,则写入 2 个字节,而不是 4 个。
-
如果您使用的是 little-endian 机器,请使用
htons()/ntohs()。见linux.die.net/man/3/ntohs
标签: c endianness