Newbie Question - Hex to floating point conversion

Tim Peters tim.one at home.com
Fri Jan 5 03:42:29 EST 2001


[sb]
> Is there an easy way to convert 4 byte floating point numbers in IEEE
> format to they're decimal equivalents?
>
> EX.: BF 00 00 00 =  -0.5

Not really, but if you're running on IEEE-754 hardware and your native C
compiler maps "float" to 4-byte IEEE-754 floats, you can build (or read from
file, or ...) a 4-byte string containing those bytes and ask Python's std
struct module (see the docs) to interpret it as a C float (use struct's "f"
format code).

For example, here on a WinTel box:

>>> struct.unpack(">f", "\xbf\0\0\0")
(-0.5,)
>>>

The ">" in the format string forces unpack to treat the bytes as a
big-endian stream; without that, struct uses the native platform convention,
which on WinTel happens to be little-endian:

>>> struct.unpack("f", "\xbf\0\0\0")
(2.6764800668604006e-043,)
>>>

A denormal probably isn't what you expected -- so if you see stuff like that
happening, remember that you were warned about the cause <wink>.





More information about the Python-list mailing list