从二进制文件读取32位整数 [英] read 32bit integer from binary file

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

问题描述



  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;



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

  • 确保你用正确的字节顺序来解释这些字节。



    问:如果你在PC上,你的CPU可能是小尾数。你知道吗你的数据流也是小端,或者是大端?

    如果数据是大端,我会考虑标准的网络功能来容纳字节顺序: ntohl()等: http://www.retran.com/beej/htonsman.html


  • ALSO:



    遵循Hcorg和Daniel Jour的建议:不要忘记open mode参数,不要忘记检查file open错误。 >

    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

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

    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?

    解决方案

    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. 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

    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屋!

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