Newbie Question - Hex to floating point conversion

Cameron Laird claird at starbase.neosoft.com
Fri Jan 5 08:44:35 EST 2001


In article <mailman.978684186.8107.python-list at python.org>,
Tim Peters <tim.one at home.com> wrote:
>[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>.
>
>

Cogent examples.  It *is* possible, of course, to
synthesize an (abstract, and therefore portable)
algorithm to accomodate all these cases.  As one
who last needed to do so professionally about thir-
teen years ago, I can testify that these arithmetic
algorithms surprise civilians by their length and
tediousness.  It takes a fair amount of care to get
something as apparently simple as decimal represen-
tation right.  If at all possible, let us leave it
to hardware, regarded as a gift from The Great Beyond.
-- 

Cameron Laird <claird at NeoSoft.com>
Business:  http://www.Phaseit.net
Personal:  http://starbase.neosoft.com/~claird/home.html



More information about the Python-list mailing list