Reading a binary file in as hex

Julio Flores Schwarzbeck jflores at codeit.com
Tue Oct 17 17:30:16 EDT 2000


import string
str = open("binoranydata","rb").read()
hexStr=""
for x in range(0, len(str)):
     hexStr=hexStr+hex(ord(str[x]))+"\n"
print hexStr

If file "binoranydata" has the string "Hola" (w/o quotes), the script will 
print:

0x48
0x6f
0x6c
0x61

on the screen

At 09:12 PM 10/17/00 +0000, Grant Edwards wrote:
>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
>--
>http://www.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list