【问题标题】:Issue in converting little Endian hexdump output to Big Endian (C-programming)将 little Endian hexdump 输出转换为 Big Endian 的问题(C 编程)
【发布时间】: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


【解决方案1】:

您告诉fwrite 写入sizeof(int) 字节,在您的系统上计算为4 个字节(int 的大小为4)。如果你想写两个字节,就这样做:

fwrite(&swapped, 2, 1, dest_file);

【讨论】:

    【解决方案2】:

    为减少混淆,对字节重新排序的代码应使用字节(uint8char),而不是像 int 这样的多字节类型。

    交换两个字节:

    char bytes[2];
    char temp;
    
    fread(bytes, 2, 1, file1);
    
    temp = bytes[0];
    bytes[0] = bytes[1];
    bytes[1] = temp;
    
    fwrite(bytes, 2, 1, file2);
    

    如果您使用int,您可能会自欺欺人,假设它的大小为 2(而最有可能是 4),并假设您的系统如何将 int 写入文件,这可能是不正确的。如果您使用字节,则不会有任何意外 - 您的代码完全按照它的样子工作。

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 2011-02-09
      • 2020-12-01
      • 1970-01-01
      • 2018-05-15
      • 2017-08-26
      相关资源
      最近更新 更多