💬 Question: How to Decode a Hex String in Python?
Decode Hex String
To decode a hexadecimal Python string, use these two steps:
- Step 1: Call the
bytes.fromhex()method to convert the hexadecimal string to a
bytesobject. For example,
- Step 2: Call the
bytes.decode()method on the result to convert the
bytesobject to a Python string. For example,
Here’s how you can chain the two methods in a single line of Python code:
>>> bytes.fromhex('68656c6c6f').decode('utf-8') 'hello'
Here’s why you use the first part of the expression—to obtain a
bytes object first:
>>> bytes.fromhex('68656c6c6f') b'hello'
⭐ Recommended Tutorial: How to Convert a Hex String to a Bytes Object in Python?
The previous example uses the Unicode
'utf-8' encoding scheme. If you want to decode to ASCII, simply pass ‘it
'ascii' into the
bytes.decode() method like so:
>>> bytes.fromhex('68656c6c6f').decode('ascii') 'hello'
⭐ Recommended Tutorial: 4 Pythonic Ways to Convert Hex to ASCII in Python
Of course, you need to make sure that the hex string actually can be decoded, i.e., two digits together represent one Unicode or ASCII symbol. For instance, ‘68656c6c6f’ will actually decode like so:
68 --> h
65 --> e
6c --> l
6c --> l
6f --> o
Otherwise, Python will raise an error if your hex string cannot be decoded because it doesn’t decode anything in the code you chose (ASCII or Unicode etc.).
An alternative way to decode a hex string that is universal and works for both Python 2 and Python 3 on various programming environments is using the
import codecs s = '68656c6c6f' print(codecs.getdecoder('hex_codec')(s)) # b'hello'
You can replace the string variable
s with your hex string you want decoded.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.