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)

Convert it to a bytes object (Python 3):

>>> bytes.fromhex(hex_string)

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

Browse More Popular Posts

Leave a Comment