【问题标题】:Read binary file to integer range of -32767 to 32767将二进制文件读取到 -32767 到 32767 的整数范围
【发布时间】:2017-10-08 14:18:33
【问题描述】:

我需要编写一个程序来将二进制文件读取到-32767到32767的范围内。到目前为止,下面的脚本将二进制文件读取到-128到127的范围内。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  FILE *fp = NULL;
  signed char shint[2000] = "";
  int i = 0;
  size_t  bytes = 0;

  if ((fp = fopen("raw_data.ht3", "rb")) == NULL) {
    printf ("could not open file\n");
    return 0;
  }
  if ((bytes = fread(&shint, 1, 2000, fp)) > 0 ) {  //bytes more than 0
    for (i = 0; i < bytes; i++) {
      printf ("%d\n", shint[i]);
    }
  }
  fclose(fp);
  return 0;
}

关于二进制文件的更多信息,我的讲师说二进制文件应该被读入 4 字节数据(我不确定我的措辞是否正确)。数据非常大,所以我停止读取数据,直到 2000 个数据。虽然将来我需要阅读所有这些。

The final data representation

这就是我想在一天结束时绘制的方式。获得所需数据后,我将调用我们的 matlab 或 scilab。

谢谢!

【问题讨论】:

  • 您可能希望一次读取 2 或 4 个字节。 (你的问题标题建议两个字节,你的讲师说四个)。您可能可以使用fread。 (字节交换理论上是一个问题,但对于本练习,您可能可以忽略它。)
  • 如何一次读取 2 或 4 个字节?
  • 您的问题说您想要一个短 [] 数组。你的老师说你想要一个 int[] 数组。
  • @HansPassant 我认为我需要坚持每次阅读 4 个字节。
  • 为避免编译器之间的类型大小差异,如果规范是文件中的整数每个为 4 个字节,则包含&lt;stdint.h&gt; 并使用int32_t 或@987654326 是最安全的@,取决于整数应该被解释为有符号还是无符号。

标签: c binary short


【解决方案1】:

据我了解,您希望轻松访问字符和带符号的 16 位整数。

#define SIZE 2000

union
{
    char shint_c[SIZE * 2];
    short shint[SIZE];
}su;

然后在你的 if 中

fread(&su, 2, SIZE, fp)

并在循环中打印短裤

printf ("%hd\n", su.shint[i]);

或 8 位整数

printf ("%hhd\n", su.shint_c[i]);

【讨论】:

    【解决方案2】:

    我没有要测试的数据(我也没有测试我的答案),但应该是这样的:

    首先signed char shint[2000] = ""; 拥有 2000 个带符号的字符(它们确实是带符号的 8 位值,看看 here - 这是处理数据类型大小时非常方便的资源),因此您需要一些值来保存带符号的32 位(4 字节)值,这取决于您的机器架构,假设它是 32 位整数 (it is not difficult to find out),您可以将值保存在 int shint[2000] = "";

    接下来你需要注意的是函数freadhere is some friendly documentation,这个函数的第二个参数(在你的代码中是1)应该是字节数,代表你想要的数据中的单个值读取,所以在你的情况下应该是 4(字节)。其他参数应该没问题。

    编辑:为确保您正在读取 4 个字节,您确实可以使用 MariaD 给出的答案并存储 long 值。

    【讨论】:

      【解决方案3】:

      使用4 字节表示您的输入数据,即。 e.替换

      signed char shint[2000] = "";
      

      long int shint[2000] = "";
      

       if ((bytes = fread(&shint, 1, 2000, fp)) > 0 ) {  //bytes more than 0
      

       if ((bytes = fread(&shint, 4, 2000, fp)) > 0 ) {  //bytes more than 0
      

      printf ("%d\n", shint[i]);
      

      printf ("%ld\n", shint[i]);
      

      注意:

      根据您的变量名称(shint,即short int)和-32768+32767 的范围,您的教师似乎想要2 字节作为数字,而不是4
      在这种情况下,在您的声明中使用short int(或简单地使用short),并将2 作为fread() 函数的第二个参数。

      【讨论】:

      • long int 不保证为 4 个字节。
      • 他需要 2 个字节而不是 4 个
      猜你喜欢
      • 2013-09-04
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 2011-09-09
      • 2018-04-16
      相关资源
      最近更新 更多