How to Decode a Hex String in Python?

4.5/5 - (2 votes)

💬 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 bytes object. For example, bytes.fromhex('68656c6c6f') yields b'hello'.
  • Step 2: Call the bytes.decode() method on the result to convert the bytes 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')

Here’s why you use the first part of the expression—to obtain a bytes object first:

>>> bytes.fromhex('68656c6c6f')

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')

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'
# b'hello'

You can replace the string variable s with your hex string you want decoded.