【问题标题】:Reading a 32 bit floating point binary data file (little endian)读取 32 位浮点二进制数据文件(小端)
【发布时间】:2015-12-22 20:30:24
【问题描述】:

我想在 python 中读取一个包含 32 位浮点二进制数据的二进制数据文件。我尝试在文件上使用 hexdump,然后在 python 中读取 hexdump。转换回浮点数时的某些值返回了 nan。我检查了在组合 hexdump 值时是否犯了错误,但找不到任何值。这就是我在 shell 中所做的:

hexdump -vc >> output.txt

输出的形式是 c0 05 e5 3f ... 以此类推

我加入十六进制为:'3fe505c0'

这是正确的方法吗?

【问题讨论】:

    标签: python-2.7 floating-point 32-bit


    【解决方案1】:

    没有。

    >>> import struct
    >>> struct.unpack('<f', '\xc0\x05\xe5\x3f')
    (1.7892379760742188,)
    

    【讨论】:

    • 好的先生,所以如果我做 struct.unpack('
    • 直接从二进制文件中读取字节并使用它们。
    • 好的,先生。所以就像 hex = file.read(8) 并将其输入到 unpack 命令中?
    • 32 位是 4 个字节,但是是的。
    • 我试过 open ('data', 'r') as file , byte = file.read(4) , print struct.unpack('
    【解决方案2】:

    这是一个写入和读取文件的示例(因此您可以看到以一些舍入误差为模得到正确答案)。

    import csv, os
    import struct
    
    test_floats = [1.2, 0.377, 4.001, 5, -3.4]
    
    ## write test floats to a new csv file:
    path_test_csv = os.path.abspath('data-test/test.csv')
    print path_test_csv
    test_csv = open(path_test_csv, 'w')
    wr = csv.writer(test_csv)
    for x in test_floats:
        wr.writerow([x])
    test_csv.close()
    
    
    ## write test floats as binary
    path_test_binary = os.path.abspath('data-test/test.binary')
    test_binary = open(path_test_binary, 'w')
    for x in test_floats:
        binary_data = struct.pack('<f', x)
        test_binary.write(binary_data)
    test_binary.close()
    
    
    ## read in test binary
    binary = open(path_test_binary, 'rb')
    binary.seek(0,2) ## seeks to the end of the file (needed for getting number of bytes)
    num_bytes = binary.tell() ## how many bytes are in this file is stored as num_bytes
    # print num_bytes
    binary.seek(0) ## seeks back to beginning of file
    i = 0 ## index of bytes we are on
    while i < num_bytes:
        binary_data = binary.read(4) ## reads in 4 bytes = 8 hex characters = 32-bits
        i += 4 ## we seeked ahead 4 bytes by reading them, so now increment index i
        unpacked = struct.unpack("<f", binary_data) ## <f denotes little endian float encoding
        print tuple(unpacked)[0]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      • 2013-10-05
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 2015-11-11
      相关资源
      最近更新 更多