Search code examples
cbinaryshort

Read binary file to integer range of -32767 to 32767


I need to make a program to read a binary file into the range of -32767 to 32767. So far, the script below read the binary file into the range of -128 to 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;
}

More info about the binary file, my lecturer said the binary file should be read into 4 bytes data (I'm not sure my wording is right here). The data is very big so I stop the data reading till 2000 data. Though in the future I need to read all of them.

The final data representation

This is how I want to plot at the end of the day. I will call our matlab or scilab after getting the desired data.

Thanks!


Solution

  • As i understand you want easy access to chars and signed 16 bits ints.

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

    and then in your if

    fread(&su, 2, SIZE, fp)
    

    and in the loop to print shorts

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

    or 8 bits ints

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