π¬ 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 abytes
object. For example,bytes.fromhex('68656c6c6f')
yieldsb'hello'
. - Step 2: Call the
bytes.decode()
method on the result to convert thebytes
object to a Python string. For example,b'hello'.decode('utf-8')
yields'hello'
.
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.).
Codecs Package
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 codecs.getdecoder()
function.
Like so:
import codecs s = '68656c6c6f' print(codecs.getdecoder('hex_codec')(s)[0]) # b'hello'
You can replace the string variable s
with your hex string you want decoded.