Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from ASCII string encoded in Hex to plain ASCII?

Tags:

python

hex

ascii

People also ask

How do you decode a hex encoded string in Python?

The easiest way to convert hexadecimal value to string is to use the fromhex() function. This function takes a hexadecimal value as a parameter and converts it into a string. The decode() function decodes bytearray and returns a string in utf-8 format.


A slightly simpler solution:

>>> "7061756c".decode("hex")
'paul'

No need to import any library:

>>> bytearray.fromhex("7061756c").decode()
'paul'

>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'                                                                          

i'm just having fun, but the important parts are:

>>> int('0a',16)         # parse hex
10
>>> ''.join(['a', 'b'])  # join characters
'ab'
>>> 'abcd'[0::2]         # alternates
'ac'
>>> zip('abc', '123')    # pair up
[('a', '1'), ('b', '2'), ('c', '3')]        
>>> chr(32)              # ascii to character
' '

will look at binascii now...

>>> print binascii.unhexlify('7061756c')
paul

cool (and i have no idea why other people want to make you jump through hoops before they'll help).


In Python 2:

>>> "7061756c".decode("hex")
'paul'

In Python 3:

>>> bytes.fromhex('7061756c').decode('utf-8')
'paul'

b''.fromhex('7061756c')

use it without delimiter