我想在python中读取包含32位浮点二进制数据的二进制数据文件。我尝试在文件上使用hexdump,然后在python中读取hexdump。转换回float时的一些值返回nan。我检查了我是否在组合hexdump值时出错,但找不到任何值。这就是我在shell中做到的:
hexdump -vc>> output.txt的
输出的形式 c0 05 e5 3f ......等等
我加入了十六进制:'3fe505c0'
这是正确的方法吗?
答案 0 :(得分:4)
没有
>>> import struct
>>> struct.unpack('<f', '\xc0\x05\xe5\x3f')
(1.7892379760742188,)
答案 1 :(得分:0)
这是一个写作的例子,读取文件(所以你可以看到你得到正确的答案模数一些舍入错误)。
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]