Question

I am writing a float32 to a file with numpy's tofile().

float_num = float32(3.4353)
float_num.tofile('float_test.bin')

It can be read with numpy's fromfile(), however that doesn't suit my needs and I have to read it as a raw binary with the help of the bitstring module.

So I do the following:

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_

Output:

3.4353
-5.56134659129e+32

What could be the cause? The second output should also be 3.4353 or close.

Était-ce utile?

La solution

The problem is that numpy's float32 is stored as little endian and bitstrings default implementation is bigendian. The solution is to specify little endian as the data type.

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_

Output:

3.4353
3.43530011177

Reference on bitstring datatypes, here.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top