convert floats to their 4 byte representation

Alex Martelli aleax at mac.com
Wed Jun 14 11:16:56 EDT 2006


godavemon <davefowler at gmail.com> wrote:

> I need to take floats and dump out their 4 byte hex representation.
> This is easy with ints with the built in hex function or even better
> for my purpose
> 
> def hex( number, size ):
>       s = "%"+str(size) + "X"
>       return (s % number).replace(' ', '0')
> 
> but I haven't been able to find anything for floats.  Any help would be
> great.

floats' internal representation in Python is 8 bytes (equivalent to a C
"double").  However, you can import struct and use struct.pack('f',x) to
get a 4-byte ("single precision") approximation of x's 8-byte value,
returned as a string of 4 bytes; you may force little-endian by using as
the format '<f' or big-endian by using '>f'; then loop on each character
of the string and get its ord(c) [a number from 0 to 255] to format as
you wish.

For example

import struct
def float_hex4(f):
    return ''.join(('%2.2x'%ord(c)) for c in struct.pack('f', f))

or variants thereof.


Alex



More information about the Python-list mailing list