Reading a binary file
Steven Taschuk
staschuk at telusplanet.net
Thu Jun 26 08:50:15 EDT 2003
Quoth Sorin Marti:
[...]
> 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?)
200, actually; hex C = 12, so hex C8 = 12*16 + 8 = 200.
Each byte represents a number in the range [0..255]. Those
numbers may be obtained with the ord function, as Andrew noted:
>>> bytes = file('foo.py', 'rb').read(10)
>>> bytes
'def inplac'
>>> map(ord, bytes)
[100, 101, 102, 32, 105, 110, 112, 108, 97, 99]
These are numbers, so you can, e.g., do arithmetic with them.
They are neither hex numbers nor decimal numbers; 'hex' and
'decimal' describe notations by which numbers may be represented,
not numbers themselves. So, when you ask for the hex value, it
seems you want a string containing characters which represent the
number in hexadecimal notation. The hex function does that, again
as Andrew noted:
>>> numbers = map(ord, bytes)
>>> [hex(num)[2:] for num in numbers]
['64', '65', '66', '20', '69', '6e', '70', '6c', '61', '63']
(I've cut out the leading '0x' which this function produces.) As
you've discovered, binascii.hexlify does this all in one step --
turns a string containing bytes into a string containing
hexadecimal digits representing the bytes:
>>> import binascii
>>> binascii.hexlify(bytes)
'64656620696e706c6163'
If, for some reason, you wanted to obtain numbers from such a
string, you could do it this way, for example:
>>> def hex2numbers(s):
... numbers = []
... for i in range(0, len(s), 2):
... numbers.append(int(s[i:i+2], 16))
... return numbers
...
>>> hex2numbers(binascii.hexlify(bytes))
[100, 101, 102, 32, 105, 110, 112, 108, 97, 99]
--
Steven Taschuk staschuk at telusplanet.net
"I tried to be pleasant and accommodating, but my head
began to hurt from his banality." -- _Seven_ (1996)
More information about the Python-list
mailing list