convert floats to their 4 byte representation

Scott David Daniels scott.daniels at acm.org
Wed Jun 14 11:50:25 EDT 2006


godavemon 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')

This should be a trifle nicer:
     def hexx(number, size):    # don't shadow the "hex" builtin
         s = "%0s" + str(size) + "X"
         return s % number

> but I haven't been able to find anything for floats.  Any help would be
> great.

Getting to float bytes is tougher.
First, python Floats are C Doubles, so you probably mean 8=byte hex.

     import array

     def eights(number, swap=False):
         data = array.array('d', [number])
         if swap:
             data.byteswap()
         return ' '.join(hexx(ord(char), 2) for char in data.tostring())

     def fours(number, swap=False):
         data = array.array('f', [number])
         if swap:
             data.byteswap()
         return ' '.join(hexx(ord(char), 2) for char in data.tostring())

--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list