literal hex value to bin file.

yaipa h. yaipa at
Fri Oct 8 06:51:48 CEST 2004

Peter L Hansen <peter at> wrote in message news:<DaKdnbopTNVBvfjcRVn-jQ at>...
> yaipa h. wrote:
> > Sorry if this has been asked before, doing a search on c.l.p, I didn't
> > find this particular use case.
> > 
> > I wish to use the struct module, in windows, to pack hexdigits in such
> > a way that when I pack, say 0xa into a packed object, I can then use
> > it to find 0xa in a binary file.
> The question is unclear to me, but wouldn't just using "\x0a"
> build a string (i.e. a 'byte sequence') with identical contents?
> A "packed object" from struct is merely a string.
> > Likewise, I wish to build a hex sequence from an Assembly language
> > .lst (text)file so that I can search for that sequence of hex digits
> > in a binary file.
> Unclear.  Please provide examples of before and after cases
> of each thing mentioned above to help guide us...
> -Peter



I seemed to have worked it out.  The bit of code below will write the
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")
# results in the binary file 'a.hex' containing,
0xff  # only

Peter, thanks again for your attempt to understand my confusion.



More information about the Python-list mailing list