【发布时间】:2017-06-15 05:27:45
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *int_pointer = (int *) malloc(sizeof(int));
// open output file
FILE *outptr = fopen("test_output", "w");
if (outptr == NULL)
{
fprintf(stderr, "Could not create %s.\n", "test_output");
return 1;
}
*int_pointer = 0xabcdef;
fwrite(int_pointer, sizeof(int), 1, outptr);
//clean up
fclose(outptr);
free(int_pointer);
return 0;
}
这是我的代码,当我看到带有 xxd 的 test_output 文件时,它会给出以下输出。
$ xxd -c 12 -g 3 test_output
0000000: efcdab 00 ....
我希望它打印 abcdef 而不是 efcdab。
【问题讨论】:
-
问题是字节序转换引起的。您可能想在这里阅读更多相关信息:gnu.org/software/libc/manual/html_node/Byte-Order.html 简而言之:整数的字节存储在内存中的顺序与它们在程序中的写入顺序不同。
-
阅读字节序,例如en.wikipedia.org/wiki/Endianness
标签: c file memory malloc endianness