binary floats

Fredrik Lundh fredrik at pythonware.com
Thu Apr 26 10:42:59 EDT 2001


Mike Morasky write:
> Anyone know how to turn 4 bytes into a float?
> These are raw binary bytes, not pickled or marshaled.

for just a few values, you can use the struct module:

>>> struct.unpack("f", "\x00\x38\x93\x45")
(4711.0,)

for arrays of floats, use the array module.  it returns an
array object, which behaves pretty much like any other
sequence:

>>> array.array("f", "\x00\x38\x93\x45"*5)
array('f', [4711.0, 4711.0, 4711.0, 4711.0, 4711.0])

for more info, see:
http://www.python.org/doc/current/lib/module-array.html
http://www.python.org/doc/current/lib/module-struct.html

> Weta Digital

intriguing...

Cheers /F





More information about the Python-list mailing list