woshichuanqilz
V2EX  ›  问与答

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

  •  
  •   woshichuanqilz · Oct 5, 2020 · 1863 views
    This topic created in 2037 days ago, the information mentioned may be changed or developed.

    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 replies    2020-10-05 11:44:48 +08:00
    lcdtyph
        1
    lcdtyph  
       Oct 5, 2020 via iPhone
    大端续,sfmt 改一下
    lcdtyph
        2
    lcdtyph  
       Oct 5, 2020 via iPhone   ❤️ 1
    大端序
    @lcdtyph
    woshichuanqilz
        3
    woshichuanqilz  
    OP
       Oct 5, 2020
    @lcdtyph Thanks 已感谢
    peonone
        4
    peonone  
       Oct 5, 2020
    是大小端的问题,文件是小端的,你是用大端的格式读出来的,把 sfmt 改成'>f'就能得出你要的结果

    至于 3C 和'<', 内容是完全一样的,只是 Python 将 3C 这个字节用 ASCII 的形式展现出来而已 b'<'[0] == int('3C', 16)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2806 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 14:17 · PVG 22:17 · LAX 07:17 · JFK 10:17
    ♥ Do have faith in what you're doing.