Reading hex to int from a binary string

Diez B. Roggisch deets at nospam.web.de
Thu Oct 8 23:13:48 CEST 2009


Luc schrieb:
> Hi all,
> 
> I read data from a binary stream, so I get hex values as characters
> (in a string) with escaped x, like "\x05\x88", instead of 0x05.
> 
> I am looking for a clean way to add these two values and turn them
> into an integer, knowing that calling int() with base 16 throws an
> invalid literal exception.
> 
> Any help appreciated, thanks.

Consider this (in the python interpreter):

 >>> chr(255)
'\xff'
 >>> chr(255) == r"\xff"
False
 >>> int(r"ff", 16)
255

In other words: no, you *don't* get hex values. You get bytes from the 
stream "as is", with python resorting to printing these out (in the 
interpreter!!!) as "\xXX". Python does that so that binary data will 
always have a "pretty" output when being inspected on the REPL.

But they are bytes, and to convert them to an integer, you call "ord" on 
them.

So assuming your string is read bytewise into two variables a & b, this 
is your desired code:

 >>> a = "\xff"
 >>> b = "\xa0"
 >>> ord(a) + ord(b)
415


HTH, Diez



More information about the Python-list mailing list