I am having some trouble with packing and unpacking of binary floats in python when doing a binary file write. Here is what I have done:
import struct
f = open('file.bin', 'wb')
value = 1.23456
data = struct.pack('f',value)
f.write(data)
f.close()
f = open('file.bin', 'rb')
print struct.unpack('f',f.read(4))
f.close()
The result I get is the following:
(1.2345600128173828,)
What is going on with the extra digits? Is this a rounding error? How does this work?
pack() is the function that converts a given list of values into their corresponding string representation. It requires the user to specify the format and order of the values that need to be converted.
unpack() This function unpacks the packed value into its original representation with the specified format. This function always returns a tuple, even if there is only one element.
The module struct is used to convert the native data types of Python into string of bytes and vice versa. We don't have to install it. It's a built-in module available in Python3. The struct module is related to the C languages.
On most platforms, Python floats are what C would call a double
, but you wrote your data out as float
instead, which has half the precision.
If you were to use double
, you'd have less precision loss:
>>> data = struct.pack('d',value)
>>> struct.unpack('d',data)
(1.23456,)
>>> data = struct.pack('f',value)
>>> struct.unpack('f',data)
(1.2345600128173828,)
The float
struct format offers only single precision (24 bits for the significant precision).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With