简体   繁体   English

从二进制文件中读取DWORD

[英]Reading DWORD from binary file

Why these lines of code doesn't work when i try to read a DWORD num = 1880762702 using fread(&num, "file path", 1, FILE*); 当我尝试使用fread(&num, "file path", 1, FILE*);读取DWORD num = 1880762702时,为什么这些代码行不起作用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. 我得到result = 10574如果我将数字更改为任何其他数字说2880762702然后它才有效。

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 . 要读取多字节数量(如DWORD(对于32位数字为Win32),您需要了解字节顺序 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. fread()的第二个参数是您要读取的数据的大小。 In your case, that's sizeof(DWORD) . 在你的情况下,这是sizeof(DWORD)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM