我写了一个程序将数字写入二进制文件,片段如下:
u_int16_t N=150;
u_int16_t seed=3;
FILE * outfile, *infile;
outfile=fopen("tempfile","wb");
//write these 2 16-bit numbers into binary file
fwrite(&seed, 2, 1, outfile);
fwrite(&N, 2, 1, outfile);
infile=fopen("tempfile","rb");
if(infile==NULL) fputs("Fire error\n",stderr);
//get the size of the file
fseek(infile,0,SEEK_END);
int lsize=ftell(infile);
rewind(infile);
u_char * temp2=(u_char*)malloc(lsize);
if(temp2==NULL) printf("temp2 error allocation\n");
fread(temp2,1,lsize,infile);
for(i=0;i<lsize;i++)
printf("%x",temp2[i]);
printf("\n");
fclose(infile);
free(temp2);
结果是:
30960
所以 3 被打印为 30
,这是小端
而 150 打印为 960
,还有一个附加的 0
,实际上是 0x96=150
,所以它是大端
为什么 3
和 150
的字节顺序不同,为什么还有一个额外的 0
?
谢谢!
最佳答案
当你做的时候
printf("%x",temp2[i]);
在十六进制数中有前导零的字节打印时没有那个零。这意味着诸如 0x03
之类的数字将打印为 3
。
这很明显,因为您向文件写入了四个字节,但打印输出中只有五个十六进制数字(提示:四个字节是八个十六进制数字)。
而是做例如
printf("%02x",temp2[i]);
关于c - 二进制文件中的字节顺序不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15634170/