Reading a binary file
Andrew Bennetts
andrew-pythonlist at puzzling.org
Thu Jun 26 08:55:01 EDT 2003
On Thu, Jun 26, 2003 at 11:33:20AM +0200, Sorin Marti wrote:
> Andrew Bennetts wrote:
> >On Thu, Jun 26, 2003 at 10:01:06AM +0200, Sorin Marti wrote:
> >
> >>But now I need the hex values of the binary file.
> >
> >You can get the hex value of a 1-character string with hex(ord(char)),
> >e.g.:
> >
> > >>> char = 'a'
> > >>> hex(ord(char))
> > '0x61'
> >
>
> That is not exactly what I meant. I've found a solution (a is the binary
> data):
>
> b = binascii.hexlify(a)
>
> For example it gives me C8 which is a HEX-Value. How to change this one
> into a decimal? (The decimal should be 130, right?)
I think you might be confused about how bytes and numbers are related. Have
a look at this:
>>> char = 'a'
>>> ord(char)
97
>>> type(ord(char))
<type 'int'>
>>> type(hex(ord(char)))
<type 'str'>
So I'm guessing you don't really want the hex representation at all!
A quick way to convert a string of bytes into the corresponding numerical
values is:
>>> s = 'hello'
>>> map(ord, s)
[104, 101, 108, 108, 111]
or:
>>> s = 'hello'
>>> [ord(char) for char in s]
[104, 101, 108, 108, 111]
And again, I *strongly* suggest you look at the struct module -- I'm not
sure what you're trying to do, but if you're trying to interpret binary data
into numbers and things, it's almost certainly helpful:
http://python.org/doc/current/lib/module-struct.html
e.g.:
>>> s = 'hello'
>>> struct.unpack('5B', s)
(104, 101, 108, 108, 111)
-Andrew.
More information about the Python-list
mailing list