Learn about Convert Hex String to ASCII String in Python in the below code example. Also, refer to the comments in the code snippet to get a detailed view about what’s actually happening.
Contents
Convert Hex String to ASCII String in Python
The bytearray.decode(encoding, error)
function in Python3 accepts a byte array as input and decodes it according to the encoding scheme given in the encoding parameter.
To decode a string in Python 3, we must first convert it to a byte array and then use the bytearray.decode()
method. To begin, use the bytearray.fromhex(string)
method to convert the string to a byte array.
hex_str = "0x865a6c"[2:]
# convert hex string to ASCII string
bytes_array = bytes.fromhex(hex_str)
The example code below shows how to use Python’s bytearray.decode() and bytearray.fromhex(string) methods to convert a hex string to an ASCII string.
Program :
# Python program to convert hex string to ASCII string
# hexadecimal string
hex_str = "0x68656c6c6f"[2:]
# convert hex string to ASCII string
bytes_array = bytes.fromhex(hex_str)
ascii_str = bytes_array.decode()
# printing ASCII string
print('ASCII String:', ascii_str)
Output:
ASCII String: hello
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Code : Python program to convert Fahrenheit to Celsius