Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Packing and Unpacking binary float in python

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?

like image 462
Wilsonator Avatar asked Apr 23 '13 09:04

Wilsonator


People also ask

What is Python pack?

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.

What is struct unpack in Python?

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.

How do you use structures in Python?

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.


1 Answers

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).

like image 125
Martijn Pieters Avatar answered Sep 21 '22 15:09

Martijn Pieters