Reading a binary file in as hex

Grant Edwards grante at visi.com
Tue Oct 17 17:12:29 EDT 2000


In article <8sicku$91r$1 at nnrp1.deja.com>, alfred6465 at my-deja.com wrote:

>I am new to python and am kinda stuck on something.  I have a binary
>file which I would like to read as hexidecimal.  The file can vary in
>length.  After I get it in a hex format I want to scan through it to
>look for certain numbers.  Any thoughts on how to do this?

I'm not sure what you mean by "read as hexidecimal".

If you want to read the bytes in a file and convert each to a
hex string, you can do something like this:

import string
d = open("file.data","rb").read()
l = map(lambda x: '%02x' % ord(x), d)
s = string.join(l)
print s

Or mashed into a one-liner:

string.join(map(lambda x: '%02x' % ord(x), open("file.data","rb").read()))

If you've got Python 2.0 you can use a list comprehension
rather than the Schemesque map/lambda

-- 
Grant Edwards                   grante             Yow!  But they went to MARS
                                  at               around 1953!!
                               visi.com            



More information about the Python-list mailing list