literal hex value to bin file.

Peter L Hansen peter at engcorp.com
Fri Oct 8 10:17:59 EDT 2004


yaipa h. wrote:
> I seemed to have worked it out.  The bit of code below will write the
> actual
> hex string literal to a binary file as is.  What I kept getting was
> the hexascii representation of the hex string, so that '9' would write
> to file as 0x39 and 'a' would write to the file as 0x61. What I wanted
> was '9' to write to the file as 0x09 and '7f' to write out as 0x7f.
> 
> #-----------------------------------------------
> import struct
> 
> a = struct.pack('B', int('ff', 16))
> 
> fh = open("a.hex", "wb")
> fh.write(a)
> fh.close()
> #-----------------------------------------------
> # results in the binary file 'a.hex' containing,
> 0xff  # only

Yep, you've got it.  As Paul suggests, chr() works nicely
for a single byte though.

Also investigate the binascii module, specifically the
hexlify() and unhexlify() methods, which work nicely on
entire strings of 2-digit hex values:

 >>> import binascii
 >>> binascii.unhexlify('097f')
'\t\x7f'
 >>> chr(9) + chr(0x7f)
'\t\x7f'
 >>> struct.pack('BB', int('09', 16), 0x7f)
'\t\x7f'

All of those are of course the same... depends on your
needs.

(Note that the output is the repr() value of the string,
which in this case contains an ASCII 9 and 7F, thus the
\t or TAB escape sequence followed by the hex escape
sequence representation of the 7F byte.  Sometimes the
fact that the interactive interpreter always does a repr()
on the output of expressions can be confusing.)

-Peter



More information about the Python-list mailing list