Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding?

J. Clifford Dyer jcd at sdf.lonestar.org
Sat May 24 19:21:01 EDT 2008


On Sat, 2008-05-24 at 15:36 -0700, zxo102 wrote:
> Hi,
>    how  to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to
> "\xED\x6F\x3C\x01" in python coding?
> When I take 'ED6F3C01' as a string and insert '\x' into it, I just got
> the error information : invalid \x escape.
>    Thanks.
> 
> ouyang

A string is made up of a list of bytes, and when you use hexadecimal
character references, the \ and the x do not represent bytes on their
own, hence they cannot be manipulated as though they were individual
characters of the string.  The sequence \xNN is one byte, as a unit.  It
cannot be divided.  So if you try:

'\x%s" % 'ef'

you will get an error, because you are substituting a two-byte string
'ef', where in fact you only wanted to complete the one byte in
question.  \x can never be separated from the two hexadecimal digits
that follow it.  They must be treated as a unit.  To get the two-byte
string 'ef' converted to the one byte character '\xef', you have to find
a way to get the numerical value of ef, and create a character of that
value.  The first part is done as follows:

int('ef', 16)

which means "get the integer value of 'ef', where 'ef' is represented in
base 16.  In order to get the byte of hexadecimal numeric value 0xef,
you use the chr() function:

'\xef' == chr(int('ef', 16))

Or if you are working with unicode, use unichr() instead of chr().

If you always treat \xNN escape sequences as indivisible, you won't go
wrong.

Cheers,
Cliff




More information about the Python-list mailing list