Retrieving int from hex in a file.

Grant Edwards grante at visi.com
Mon Apr 28 10:45:23 EDT 2008


On 2008-04-28, Filipe Teixeira <filipe.tg at gmail.com> wrote:
> Hi.
>
> I have to open a binary file from an old computer and recover the
> information stored (or at least try to). I use:
>
> f=open('file.bin','rb')
> a=f.read()
> f.close()
>
> a in now a string full of hex representations in the form:
>
> a[6]='\x14'
> a[7]='\x20'

a is now a string of binary data.  It doesn't contain a "hex
representation" of anything.  Hex is a way of printing stuff on
paper or on a screen.  Python doesn't store anything in hex.

> I would like to convert these hex representations to int,

That's your mistake: you don't have hex data. Nothing is being
stored in hex in your example.

> but this (the most obvious way) doesn't seem to be working
>
>>>> q=a[6]
>>>> q
> '\x14'
>>>> int(q,16)

That converts a hex string into an integer, you've not got a
hex string.  You have a string containing binary data.

"4A4B4C" is a hex string.  It's 6 bytes long and contains the
ASCII characters '4' 'A' '4' 'B' '4' 'C'.

"\x4a\x4b\4c" is just a three-byte long chunk of binary data.
It was _typed_ in hex, but it's stored in binary not in hex.
It's identical to "JKL".

> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int():
>>>>
>
> How can I do this?

You can use the struct module, or you can do it explicitly like
this:

>>> a = 'abcdef\x12\x34qwer'
>>> n = (ord(a[6])<<8) | ord(a[7])
>>> n
4660
>>> hex(n)
'0x1234'
>>> 

-- 
Grant Edwards                   grante             Yow! When you get your
                                  at               PH.D. will you get able to
                               visi.com            work at BURGER KING?



More information about the Python-list mailing list