How to convert hexadecimal string to bytes in Python?

Suppose your hex string is something like

>>> hex_string = "deadbeef"

Convert it to a bytearray (Python 3 and 2.7):

>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')

Convert it to a bytes object (Python 3):

>>> bytes.fromhex(hex_string)
b'\xde\xad\xbe\xef'

Note that bytes is an immutable version of bytearray.

Convert it to a string (Python ≤ 2.7):

>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"

Leave a Comment