读取二进制文件到 -32767 到 32767 的整数范围

Read binary file to integer range of -32767 to 32767

我需要编写一个程序来将二进制文件读取到-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。

谢谢!

使用 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() 函数的第二个参数。

我没有你的数据可以测试(我也没有测试我的答案)但它应该是这样的:

首先,signed char shint[2000] = ""; 持有 2000 个带符号的字符(确实是带符号的 8 位值,看看 here - this is a very handy resource when handling data types sizes) , so you need some value to hold signed 32 bit (4 byte) values, which depends on your machine architecture, assuming it is 32 bit integer (it is not difficult to find out)你可以在 int shint[2000] = "";[=16= 中持有你的值]

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

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

据我了解,您希望轻松访问字符和带符号的 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]);