简体   繁体   English

从C ++中的二进制文件读取32位整数?

[英]Read 32-bit integer from binary file in C++?

My binary file looks like this. 我的二进制文件看起来像这样。

00000000: 0000 0803 0000 ea60 0000 001c 0000 001c
00000010: 0000 0000 0000 0000 0000 0000 0000 0000

left column is address. 左栏是地址。

I just tried to read 0000 0803 (=2051) as follows 我只是尝试按如下方式读取0000 0803 (= 2051)

ifstream if;
if.open("file");
uint32_t a;
if >> a;

As expected...It did not work :-( 正如所料......它不起作用:-(
a was just 0 after execution. a执行后只有0。
I tried long, int, unsigned int, unsigned long . 我试过long, int, unsigned int, unsigned long All failed. 都失败了。

Why these are not working and how can I achieve the goal? 为什么这些不起作用,我怎样才能实现目标?

You have two issues: 你有两个问题:

  1. Insuring you read the bytes you intend (no fewer, no more) from the stream. 确保您从流中读取您想要的字节(不少,不多)。

    I'd recommend this syntax: 我推荐这种语法:

    uint32_t a;

    inFILE.read(reinterpret_cast<char *>(&a), sizeof(a));

  2. Insure you're interpreting those bytes with the correct byte order. 确保您使用正确的字节顺序解释这些字节。

    Q: If you're on a PC, your CPU is probably little endian . 问:如果你在PC上,你的CPU可能是小端 Do you know if your data stream is also little-endian, or is it big endian? 你知道你的数据流是否也是小端的,还是大端?

    If the data is big-endian, I'd consider the standard networking functions to accomodate byte order: ntohl() , etc: http://www.retran.com/beej/htonsman.html 如果数据是big-endian,我会考虑标准网络函数来容纳字节顺序: ntohl()等: http//www.retran.com/beej/htonsman.html

ALSO: 也:

Follow Hcorg's and Daniel Jour's advice: don't forget about the "open mode" parameter, and don't forget to check for "file open" errors. 按照Hcorg和Daniel Jour的建议:不要忘记“打开模式”参数,不要忘记检查“文件打开”错误。

Open file in binary mode and then use read() method, something like: 以二进制模式打开文件,然后使用read()方法,如:

uint32_t a;
ifstream file ("file", ios::in | ios::binary);
if (file.is_open())
{
     file.read ((char*)&a, sizeof(a));
}

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

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