2
我正在使用numpys tofile()
將float32寫入文件。如何從使用numpy的tofile編寫的原始二進制文件讀取浮點數()
float_num = float32(3.4353)
float_num.tofile('float_test.bin')
它可以與numpys 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_
輸出:
3.4353
-5.56134659129e+32
什麼可以原因?
在附註中,'numpy'的'tofile'寫入硬件/操作系統的本地端序列號。這些日子大部分事情都在x86硬件上運行,所以小端是常態。但是,如果您在SPARC CPU上運行,'numpy.tofile'會以big-endian順序寫入。 'bitstream'可能選擇了big-endian,因爲它是默認的「網絡」順序。你可以考慮使用內建的'struct'模塊而不是'bitstream'(儘管比特流有很多不錯的特性)。 –