我写了一个程序将数字写入二进制文件,代码片段如下:

    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,所以它是大端的
为什么3150的endianess不同,为什么还有额外的0
谢谢!

最佳答案

当你这样做的时候

printf("%x",temp2[i]);

十六进制数中前导零的字节打印时不带该零。这意味着,例如,0x03之类的数字将被打印为3
向文件中写入4个字节是很明显的,但是打印输出中只有5个十六进制数字(提示:4个字节是8个十六进制数字)。
相反,例如。
printf("%02x",temp2[i]);

关于c - 二进制文件中的字节序不一致,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15634170/

10-13 08:11
查看更多