Write an hexadecimal file

Raymond Hettinger vze4rx4y at verizon.net
Wed Mar 30 19:45:53 CEST 2005


[Cesar Andres Roldan Garcia]
> I'm trying to write an hexadecimal file... I mean not a text plain...
>I have to convert a float decimal number in float hexadecimal one,
> and that's done.

The struct module provides a portable way to convert a float to and from a
sequence of bytes.

The binascii modules provides tools for converting a sequence of bytes to and
from a representation as a hex string.

>>> import struct, binascii
>>> binascii.hexlify(struct.pack('>f', 3.1415926535))
'40490fdb'
>>> struct.unpack('>f', binascii.unhexlify(_))[0]
3.1415927410125732

Writing to a file is accomplished with the open() function and the file.write()
method:

f = open('mydata.hex', 'w')
f.write('40490fdb')
f.close()



Raymond Hettinger





More information about the Python-list mailing list