hex string to floating point (newbie)

Peter Hansen peter at engcorp.com
Mon Mar 17 09:10:09 EST 2003


zif wrote:
> 
> I would appreciate if somebody could help me solve my problem:
> I need to translate a hex string '3f8ccccd' to it's
> floating point value.

Technically, you need to specify what type of floating point 
the value represents?  Is it specific to a particularly CPU?
Some DSP chip maybe?  Or a standard format like IEEE 754?

Assuming the bytes that make up your floating point data 
were generated from Python, you could retrieve the floating
point value represented in the following way:

Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32
>>> import struct, binascii
>>> h = binascii.unhexlify('3f8ccccd')
>>> h
'?\214\314\315'
>>> print struct.unpack('<f', h)[0]
-428967904.0
>>> print struct.unpack('>f', h)[0]
1.10000002384

The reason there are two possible results is that you haven't
specified the byte-ordering of the floating point data.  One 
could guess, perhaps correctly, by its form that it's big-endian, 
in which case the big negative value is possibly what you want.
See details in the docs for binascii and struct to learn more.

-Peter




More information about the Python-list mailing list