How to Convert a String from Hex to ASCII in Python
In this tutorial, we will learn how to convert a hexadecimal string from its base-16 encoding into its ASCII representation.
To do this we will need to perform two operations. The first is to create a bytes object from the hex string using the Python bytes.fromhex()
function and convert that object into an ASCII string using the Python .decode()
function.
hex_str = '68656c6c6f'
bytes_obj = bytes.fromhex(hex_str)
ascii_str = bytes_obj.decode('ASCII')
print(ascii_str)
hello
If there is a 0x
at the start of your hex string slice it away like this:
hex_str = '0x68656c6c6f'[2:]
bytes_obj = bytes.fromhex(hex_str)
ascii_str = bytes_obj.decode('ASCII')
print(ascii_str)
hello