godavemon <[EMAIL PROTECTED]> 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 -- http://mail.python.org/mailman/listinfo/python-list