c - 二进制文件中的字节顺序不一致

标签 c binaryfiles endianness

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

    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 的字节顺序不同,为什么还有一个额外的 0 ? 谢谢!

最佳答案

当你做的时候

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

在十六进制数中有前导零的字节打印时没有那个零。这意味着诸如 0x03 之类的数字将打印为 3

这很明显,因为您向文件写入了四个字节,但打印输出中只有五个十六进制数字(提示:四个字节是八个十六进制数字)。

而是做例如

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

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

相关文章:

cvs - 如何从命令行CVS提交二进制文件?

javascript - 纯 JavaScript 二进制操作

c++ - 为什么在 C++ 中字节数组中的字节是颠倒的

c - omp parallel 用于输出顺序

c - 长文本字符串中的模式匹配

C- 检查字符串中的字符是否属于数组

c - 执行此按位运算以模拟 RRC 指令的目的是什么

c - C 中的 Pthread 加入?

c# - BinaryFormatter 字节顺序

python - 为什么 python 的结构认为 little-endian 和 big-endian 意味着不同的长度?