用python从二进制文件中读取32位有符号ieee 754浮点数? [英] Reading 32 bit signed ieee 754 floating points from a binary file with python?
问题描述
我有一个二进制文件,这是一个简单的有符号的32位ieee754浮点数列表。它们之间没有任何分隔,只是一个接一个地出现,直到EOF。
我如何从这个文件读取并正确解释为浮点数?
我试过使用 read(4)
,但它会自动将它们转换为ASCII编码的字符串。
我也尝试过使用 bytearray
,但是只占用1个字节,而不是4个字节我需要的时间。
struct.unpack('f',file.read (4))
你也可以一次解包几个,速度会更快:
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
I have a binary file which is simple a list of signed 32 bit ieee754 floating point numbers. They are not separated by anything, and simply appear one after another until EOF.
How would I read from this file and interpret them correctly as floating point numbers?
I tried using read(4)
, but it automatically converts them to a string with ascii encoding.
I also tried using bytearray
but that only takes it in 1 byte at a time instead of 4 bytes at a time as I need.
struct.unpack('f', file.read(4))
You can also unpack several at once, which will be faster:
struct.unpack('f'*n, file.read(4*n))
这篇关于用python从二进制文件中读取32位有符号ieee 754浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!