从C ++中的二进制文件读取32位整数? [英] Read 32-bit integer from binary file in C++?

查看:253
本文介绍了从C ++中的二进制文件读取32位整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的二进制文件如下所示。

My binary file looks like this.

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

左列是地址。

我只是尝试如下读取 0000 0803 (= 2051)

I just tried to read 0000 0803(=2051) as follows

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

按预期方式...它没有用:-(

a 执行后仅为0。

我尝试了 long,int,unsigned int,unsigned long 。全部失败。

As expected...It did not work :-(
a was just 0 after execution.
I tried long, int, unsigned int, unsigned long. All failed.

为什么这些都不起作用,我怎么能达到目标?

Why these are not working and how can I achieve the goal?

推荐答案

您有两个问题:


  1. 确保您读取了想要的字节(不少于,无

  1. Insuring you read the bytes you intend (no fewer, no more) from the stream.

我建议使用以下语法:

uint32_t a;

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

请确保您以正确的字节顺序解释这些字节。

Insure you're interpreting those bytes with the correct byte order.

问:如果您使用的是PC,则您的CPU可能是 little endian 。您的数据流也是小端的,还是大端的?

Q: If you're on a PC, your CPU is probably little endian. Do you know if your data stream is also little-endian, or is it big endian?

如果数据是大端的,我会考虑andard网络功能以适应字节顺序: ntohl(),等等: http ://www.retran.com/beej/htonsman.html

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

ALSO:

遵循Hcorg和Daniel Jour的建议:不要忘记打开模式参数,也不要忘记检查文件打开错误。

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.

这篇关于从C ++中的二进制文件读取32位整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆