How to Convert Hexadecimal Strings to ASCII in Python
This guide explains how to convert a hexadecimal string (e.g., "7475746F7269616C"
) to its corresponding ASCII representation (e.g., "tutorial"
) in Python. We'll cover the most efficient and Pythonic methods using bytes.fromhex()
, the binascii
module, and the codecs
module. We'll also briefly touch on a manual approach (which is less efficient and not recommended).
Using bytes.fromhex()
(Recommended)
The bytes.fromhex()
method (or, equivalently, bytearray.fromhex()
) is the most direct and efficient way to convert a hexadecimal string to a bytes object, which can then be decoded to an ASCII string:
hex_str = '7475746F7269616C7265666572656E63652E636F6D'
result = bytes.fromhex(hex_str).decode('ascii') # Or 'utf-8' if appropriate
print(result) # Output: tutorialreference.com
bytes.fromhex(hex_str)
: Converts the hexadecimal stringhex_str
into abytes
object. This method ignores whitespace, sobytes.fromhex('62 6f 62')
is equivalent tobytes.fromhex('626f62')
..decode('ascii')
: Decodes thebytes
object into a string using the ASCII encoding. If your original string used a different encoding (e.g., UTF-8, and contains non-ASCII characters), use that encoding instead. If you are unsure, try decoding usingutf-8
.- You can also create a
bytearray
object:
hex_str = '7475746F7269616C7265666572656E63652E636F6D'
result = bytearray.fromhex(
hex_str
).decode()
print(result) # Output: tutorialreference.com
Using binascii.unhexlify()
The binascii.unhexlify()
function is another way to convert a hexadecimal string to a bytes
object:
import binascii
hex_str = '7475746F7269616C7265666572656E63652E636F6D'
as_bytes = binascii.unhexlify(hex_str)
print(as_bytes) # Output: b'tutorialreference.com'
as_string = as_bytes.decode('ascii') # Or 'utf-8' if appropriate
print(as_string) # Output: tutorialreference.com
binascii.unhexlify(hex_str)
: Converts the hex string to abytes
object..decode('ascii')
: Decodes the bytes to a string.
Using codecs.decode()
The codecs.decode()
function provides a general way to decode data using various codecs, including 'hex':
import codecs
hex_str = '7475746F7269616C7265666572656E63652E636F6D'
as_bytes = codecs.decode(hex_str, 'hex')
print(as_bytes) # Output: b'tutorialreference.com'
as_string = as_bytes.decode('ascii') # Or 'utf-8'
print(as_string) # Output: tutorialreference.com
- The
codecs.decode(hex_str, 'hex')
method converts the hex string into a bytes object.
Manual Conversion (Not Recommended)
You could manually convert the hexadecimal string to ASCII by iterating over pairs of hex characters, converting them to integers, and then to characters. This is significantly less efficient and more complex than the built-in methods and is strongly discouraged.
hex_str = '7475746F7269616C7265666572656E63652E636F6D'
result = ''.join(
chr(int(''.join(char), 16))
for char in zip(hex_str[0::2], hex_str[1::2])
)
print(result) # Output: tutorialreference.com