开发者

Reading DWORD from binary file

Why these lines of code doesn't work 开发者_JAVA百科when i try to read a DWORD num = 1880762702 using fread(&num, "file path", 1, FILE*); I get the result = 10574 if I change the num to any other number say 2880762702 only then it works.


To read a multibyte quantity such as a DWORD (which is Win32-speak for a 32-bit number) you need to be aware of endianness. It's best to read the number one byte at a time, and convert from the byte ordering used in the file.

FILE *in;
DWORD num = 0;

if((fin = fopen("filename.bin", "rb")) != NULL)
{
  unsigned char b0, b1, b2, b3;

  fread(&b3, sizeof b3, 1, in);
  fread(&b2, sizeof b2, 1, in);
  fread(&b1, sizeof b1, 1, in);
  fread(&b0, sizeof b0, 1, in);

  // Assuming file is big-endian.
  // for little endian, swap the order to b0...b3
  num = (((DWORD) b3) << 24) | (((DWORD) b2) << 16) | (((DWORD) b1) << 8) | b0;

  fclose(in);
}


The second parameter to fread() is the size of the data you want to read. In your case, that's sizeof(DWORD).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜