开发者

Reading in 32 bit binary in C

Very new to C / C++ and I am struggling here. I have a .bin file with 32-bit signed integers in hex I wish to read in. I first need to read in the first two numbers as these contain information about hte rest of the data but I can't even get this correct. A test file has

00000004
00000003

as the first two numbers running my code gives me 808464394 for my data size variable. I've tried specifying the printf format as %lx as well just in-case I'm screwing up on the printf formatting.

I've chosen a long int to read my data into as I understand a long in is 32 bit signed so that that would be the best choose. Later on I will however need to chop up each long and look at groups of bits within the long.

Could someone please advice me as to why the numbers being printed out are not the ones I want. Also if long int is not a suitable data type co开发者_高级运维uld you please suggest an alternative.

Code attached below.

Thank you

int getsizes(long &data_size, long &image_size);

int main()
{

  long* data = NULL; // pointer of arry we will read data into.
  long data_size, image_size;

  // get data_size and image_size from task1.bin

   if (getsizes(data_size,image_size)) cerr << "Error getting data_size,image_size" ;


  int Idata_size = (int) data_size; // creat my array to store rest of file in
  data = new long[Idata_size];

  // get rest of data (still to do)

  // interprate data operations (still todo).


  delete [] data;  // freeing memory just for completeness even though program is about to exit.
  data = NULL;

  return 0;
}


\\functions


int getsizes(long &data_size, long &image_size)
{

  FILE *fp;


  fp=fopen("test01.bin", "rb"); // open for reading
  if (fp==0) cerr << "Error openeing file"<<endl;

  fread(&data_size, sizeof(data_size), 1, fp); //sizeof(data_size) should be 32

  fread(&image_size, 32, 1, fp);

  #ifdef DEBUG
    printf ("data_size= %ld \n", data_size);
    cout <<"call4" <<endl;
    printf ("image_size= %ld \n", image_size);
  #endif

  fclose(fp); // 

  return 0; // succsess.

}


You are reading the decimal representations of the numbers directly into numbers in memory. The number 808464394 is 0x30303030, which is a sequence of four zeros (the first four bytes of your input file), when interpreted as ASCII.

Use fscanf instead of fread.


Another issue is that your test input is not a binary file, it is a text file.

A binary file is generally written by another program, and when you open it in notepad it will show a bunch of unreadable symbols. If you can read the whole file when you open it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜