woshichuanqilz
V2EX  ›  问与答

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

  •  
  •   woshichuanqilz · Oct 5, 2020 · 2300 views
    This topic created in 2222 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
    lcdtyph
    Oct 5, 2020 via iPhone
    1
    大端续,sfmt 改一下
    lcdtyph
    lcdtyph
    Oct 5, 2020 via iPhone❤️1
    2
    大端序
    @lcdtyph
    woshichuanqilz
    woshichuanqilz
    OP
    Oct 5, 2020
    3
    @lcdtyph Thanks 已感谢
    peonone
    peonone
    Oct 5, 2020
    4
    是大小端的问题,文件是小端的,你是用大端的格式读出来的,把 sfmt 改成'>f'就能得出你要的结果

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