convert floats to their 4 byte representation
godavemon
davefowler at gmail.com
Wed Jun 14 12:03:32 EDT 2006
I've been a member for a while but I had no idea how helpful this form
is. I had a one hour meeting and when I came back there were 4
replies. Thanks for your help!
Scott David Daniels wrote:
> 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