Help need with converting Hex string to IEEE format float

Fredrik Lundh fredrik at pythonware.com
Tue Dec 14 10:57:02 EST 2004


<i_vincent at hotmail.com> wrote:

> Newbie Python programmer here, so please be patient. I have spent all
> day googling for an answer to my problem, but everything I try fails to
> work (or works from the Interpreter with a set value but not from my
> code with dynamic values).
>
> Okay, here is the general gist of the problem. I am using Python to
> parse an output file (from a MAK Logger but that is not really
> important). Now I have some data that is contained on a line in this
> file like:
>
> 80 00 00 00
>
> Each of these numbers is a Hex byte making up a four byte (32 bit
> Big-Endian) IEEE float. I have read this data into Python using
> readlines and then line.split(). This gives me:
>
> ['80', '00', '00', '00']

how about:

    # convert to byte string
    import struct
    s = "".join([chr(int(c, 16)) for c in x])
    v = struct.unpack("!f", s)

or

    # convert to byte string, via the array module
    import array, struct
    a = array.array("B", [int(c, 16) for c in x])
    v = struct.unpack("!f", )

</F> 






More information about the Python-list mailing list