Python 如何从用numpy'编写的原始二进制文件中读取浮点值;s tofile()

Python 如何从用numpy'编写的原始二进制文件中读取浮点值;s tofile(),python,numpy,bitstring,Python,Numpy,Bitstring,我正在用numpy的tofile()将float32写入一个文件 它可以用numpy的fromfile()读取,但是这不适合我的需要,我必须在位字符串模块的帮助下将其作为原始二进制读取 因此,我做了以下工作: my_file = open('float_test.bin', 'rb') raw_data = ConstBitStream(my_file) float_num_ = raw_data.readlist('float:32') print float_num print float

我正在用numpy的
tofile()
float32
写入一个文件

它可以用numpy的
fromfile()
读取,但是这不适合我的需要,我必须在
位字符串
模块的帮助下将其作为原始二进制读取

因此,我做了以下工作:

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_
输出:

3.4353
-5.56134659129e+32
3.4353
3.43530011177

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

问题是numpy的
float32
存储为小端,而位字符串的默认实现是bigendian。解决方案是指定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_
输出:

3.4353
-5.56134659129e+32
3.4353
3.43530011177

关于位字符串数据类型的参考,.

在旁注中,
numpy
tofile
写入硬件/OS的本机端。现在大多数东西都是在x86硬件上运行的,所以很少使用endian。但是,如果您在SPARC CPU上运行,
numpy.tofile
将以大端顺序编写
bitstream
可能选择big-endian,因为它是默认的“网络”顺序。您可以考虑使用Buffix<代码> Stutt模块,而不是<代码>比特流< /> >(虽然位流有很多漂亮的特性)。