V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
woshichuanqilz
V2EX  ›  问与答

Python 二进制读文件 转换 float 失败

  •  
  •   woshichuanqilz · 2020-10-05 11:28:09 +08:00 · 1044 次点击
    这是一个创建于 1270 天前的主题,其中的信息可能已经有所发展或是发生改变。

    python 代码

        sacfile = 'binfile'
        f = open(sacfile, 'rb')
        hdrBin = f.read()[:4]
        print(hdrBin)
        sfmt = 'f'
        hdrFmt = struct.Struct(sfmt)
        m_header = hdrFmt.unpack(hdrBin)
    

    输出结果

    b'<\xa3\xd7\n'

    但是我用 winhex 查看源文件 第一位是 3C 被转换成 '<' 了 winhex 前八个字节的数据

    3CA3D70AC7572000

    问题是我需要把前四个 byte 转换为 float 数据, 就是"m_header"

    我拿到的结果是错的: 2.0765148849577988e-32

    正确的结果应该是: 0.02000000 这个问题怎么解决?

    binfile 在这里

    https://gitee.com/lovelife_lizhe/ori_data/raw/master/binfile

    4 条回复    2020-10-05 11:44:48 +08:00
    lcdtyph
        1
    lcdtyph  
       2020-10-05 11:33:23 +08:00 via iPhone
    大端续,sfmt 改一下
    lcdtyph
        2
    lcdtyph  
       2020-10-05 11:33:46 +08:00 via iPhone   ❤️ 1
    大端序
    @lcdtyph
    woshichuanqilz
        3
    woshichuanqilz  
    OP
       2020-10-05 11:42:31 +08:00
    @lcdtyph Thanks 已感谢
    peonone
        4
    peonone  
       2020-10-05 11:44:48 +08:00
    是大小端的问题,文件是小端的,你是用大端的格式读出来的,把 sfmt 改成'>f'就能得出你要的结果

    至于 3C 和'<', 内容是完全一样的,只是 Python 将 3C 这个字节用 ASCII 的形式展现出来而已 b'<'[0] == int('3C', 16)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5526 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 07:56 · PVG 15:56 · LAX 00:56 · JFK 03:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.