How to Convert Hex to Byte in Python


If you need to convert Hex to Byte in Python, then you can do one of the following:

Option 1 – Using binascii

import binascii
str_val = 'This is a test'.encode('utf-8')
hex_val = binascii.hexlify(str_val).decode('utf-8')

print(hex_val)

Option 2 – Using bytes.fromhex()

hex_val = 'This is a test'

print(bytes.fromhex(hex_val))

Option 3 – Using unhexlify

import binascii
from binascii import unhexlify

str_val = 'This is a test'.encode('utf-8')
hex_val = binascii.hexlify(str_val).decode('utf-8')

print('String value: ', str_val.decode('utf-8'))
print('Hexadecimal: ', hex_val)
print('Byte value: ', unhexlify(hex_val))