Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert hexadecimal string to character with that code point?

I have the string x = '0x32' and would like to turn it into y = '\x32'.
Note that len(x) == 4 and len(y) == 1.

I've tried to use z = x.replace("0", "\\"), but that causes z = '\\x32' and len(z) == 4. How can I achieve this?

like image 529
Everyone_Else Avatar asked Dec 18 '22 09:12

Everyone_Else


2 Answers

You do not have to make it that hard: you can use int(..,16) to parse a hex string of the form 0x.... Next you simply use chr(..) to convert that number into a character with that Unicode (and in case the code is less than 128 ASCII) code:

y = chr(int(x,16))

This results in:

>>> chr(int(x,16))
'2'

But \x32 is equal to '2' (you can look it up in the ASCII table):

>>> chr(int(x,16)) == '\x32'
True

and:

>>> len(chr(int(x,16)))
1
like image 172
Willem Van Onsem Avatar answered Dec 20 '22 23:12

Willem Van Onsem


Try this:

z = x[2:].decode('hex')
like image 23
runcoderun Avatar answered Dec 20 '22 22:12

runcoderun