读取一个 32 位浮点二进制数据文件(little endian)

Reading a 32 bit floating point binary data file (little endian)

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

hexdump -vc >> output.txt

输出的形式是 c0 05 e5 3f ...等等

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

这是执行此操作的正确方法吗?

没有

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

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

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]