convert floats to their 4 byte representation
Tim Chase
python.list at tim.thechases.com
Wed Jun 14 11:26:42 EDT 2006
> s = "%"+str(size) + "X"
> return (s % number).replace(' ', '0')
While I don't have a fast and easy way to represent floats, you
may want to tweak this to be
return ("%0*X" % (size,number))
which will zero-pad the number in hex to "size" number of places
in a single step. It also helps prevent problems where there might
> but I haven't been able to find anything for floats. Any help
> would be great.
My first stab at such an attempt:
>>> from struct import pack, unpack
>>> s = pack("d", 3.14)
>>> i = unpack("q", s)
>>> "%X"%i
'40091EB851EB851F'
>>> def floatAsHex(f, size):
... return "%0*X" % (size, unpack("q", pack("d", f))[0])
...
>>> floatAsHex(3.14, 20)
'000040091EB851EB851F'
It's ugly, it's hackish, it's likely architecture-dependant, but
it seems to do what you're describing.
-tkc
More information about the Python-list
mailing list