如何从用 numpy 的 tofile() 编写的原始二进制文件中读取浮点数

The*_*eer 3 python numpy bitstring

我正在float32用 numpy 的tofile().

float_num = float32(3.4353)
float_num.tofile('float_test.bin')
Run Code Online (Sandbox Code Playgroud)

它可以用 numpy's 读取fromfile(),但这不符合我的需要,我必须在bitstring模块的帮助下将其作为原始二进制文件读取。

所以我执行以下操作:

my_file = open('float_test.bin', 'rb')
raw_data = ConstBitStream(my_file)
float_num_ = raw_data.readlist('float:32')

print float_num
print float_num_
Run Code Online (Sandbox Code Playgroud)

输出:

3.4353
-5.56134659129e+32
Run Code Online (Sandbox Code Playgroud)

可能是什么原因?第二个输出也应该是3.4353或关闭。

The*_*eer 5

问题是 numpyfloat32存储为小端,而位串默认实现是大端。解决方案是指定 little endian 作为数据类型。

my_file = open('float_test.bin', 'rb')
raw_data = ConstBitStream(my_file)
float_num_ = raw_data.readlist('floatle:32')

print float_num
print float_num_
Run Code Online (Sandbox Code Playgroud)

输出:

3.4353
3.43530011177
Run Code Online (Sandbox Code Playgroud)

关于位串数据类型的参考,这里

  • 附带说明一下,`numpy` 的 `tofile` 以硬件/操作系统的本机字节顺序写入。现在大多数东西都在 x86 硬件上运行,所以小端是常态。但是,如果您在 SPARC CPU 上运行,`numpy.tofile` 将按大端顺序写入。`bitstream` 可能选择了 big-endian,因为它是默认的“网络”顺序。您可能会考虑使用内置的 `struct` 模块而不是 `bitstream`(尽管 bitstream 有很多不错的功能)。 (4认同)