从二进制文件读取32位整数 [英] read 32bit integer from binary file
问题描述
00000000:0000 0803 0000 ea60 0000 001c 0000 001c
00000010: 0000 0000 0000 0000 0000 0000 0000 0000
左栏是地址。
我试图读取 0000 0803
(= 2051)如下
ifstream if;
if.open(file);
uint32_t a;
如果>>一个;
正如预期的那样...它没有工作:-(
a
在执行后只是0。 >。
为什么这些都不起作用,我该如何实现目标?
你有两个问题:$ ol
保证你读取你想要的字节数(不少于,不是)
我推荐这个语法:
uint32_t a;
确保你用正确的字节顺序来解释这些字节。 问:如果你在PC上,你的CPU可能是小尾数。你知道吗你的数据流也是小端,或者是大端? 如果数据是大端,我会考虑标准的网络功能来容纳字节顺序: ALSO: 遵循Hcorg和Daniel Jour的建议:不要忘记open mode参数,不要忘记检查file open错误。 > My binary file looks like this. left column is address. I just tried to read As expected...It did not work :-( Why these are not working and how can I achieve the goal? You have two issues: Insuring you read the bytes you intend (no fewer, no more) from the stream. I'd recommend this syntax: Insure you're interpreting those bytes with the correct byte order. 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? If the data is big-endian, I'd consider the standard networking functions to accomodate byte order: 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. 这篇关于从二进制文件读取32位整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! inFILE.read(reinterpret_cast< char *>(& a) );
ntohl()
等: http://www.retran.com/beej/htonsman.html
00000000: 0000 0803 0000 ea60 0000 001c 0000 001c
00000010: 0000 0000 0000 0000 0000 0000 0000 0000
0000 0803
(=2051) as followsifstream if;
if.open("file");
uint32_t a;
if >> a;
a
was just 0 after execution.
I tried long, int, unsigned int, unsigned long
. All failed.
uint32_t a;
inFILE.read(reinterpret_cast<char *>(&a), sizeof(a));
ntohl()
, etc: http://www.retran.com/beej/htonsman.html