binary floats

Tim Peters tim.one at home.com
Sat Apr 14 02:32:04 EDT 2001


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

See the docs for the struct module.  You're going to have to worry about
whether your data is in little-endian or big-endian format, and also whether
your raw binary bytes match the *natural* float representation on your
machine.

Here's on a little-endian WinTel box, building the largest finite IEEE-754
double by hand:

Python 2.1c1 (#13, Apr 13 2001, 13:58:40) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
IDLE 0.8 -- press F1 for help
>>> import struct
>>> raw = "\xff\xff\xff\xff\xff\xff\xef\x7f"
>>> struct.unpack("d", raw)
(1.7976931348623157e+308,)
>>>

For an IEEE single you need to use the "f" format code instead.  But note
that Python doesn't have C's single-precision floating type:  struct will
unpack one, but it will be converted to C double (== Python's float type)
before you see it.

god-created-the-integers-and-then-gave-up-in-frustration-ly y'rs  - tim





More information about the Python-list mailing list