Open In App

Convert Hex String to Bytes in Python

Last Updated : 21 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Hexadecimal strings are a common representation of binary data, especially in the realm of low-level programming and data manipulation. The task of converting a hex string to bytes in Python can be achieved using various methods. Below, are the ways to convert hex string to bytes in Python.

  • Using bytes.fromhex()
  • Using bytearray.fromhex()
  • Using binascii.unhexlify()
  • Using List Comprehension

Using bytes.fromhex()

The bytes.fromhex() method converts a hexadecimal string directly into an immutable bytes object.

Python
a = "1a2b3c"
br = bytes.fromhex(a)

print(type(a))   
print(br)       
print(type(br))

Output
<class 'str'>
b'\x1a+<'
<class 'bytes'>

Explanation: This code initializes a hex string "1a2b3c" and converts it to bytes using the `bytes.fromhex()` method and result is printed using print() statement.

Using bytearray.fromhex()

The bytearray.fromhex() method is similar to bytes.fromhex(), but it returns a mutable bytearray object. This method is particularly useful when you need to modify the byte data after conversion.

Python
a = "1a2b3c"
br = bytearray.fromhex(a)

print(type(a))      
print(br)      
print(type(br)) 

Output
<class 'str'>
bytearray(b'\x1a+<')
<class 'bytearray'>

Explanation: This code defines a hex string "1a2b3c" and converts it to a bytearray using the `bytearray.fromhex()` method, storing the result in the variable `br`.

Using binascii.unhexlify()

Python
import binascii

a = "1a2b3c"
br = binascii.unhexlify(a)

print(type(a))  
print(br)       
print(type(br))

Output
<class 'str'>
b'\x1a+<'
<class 'bytes'>

Explanation: This code uses the `binascii` module to convert the hex string "1a2b3c" to bytes using the `unhexlify()` function. The resulting bytes are stored in the variable `br` and result is displayed.

Using List Comprehension

This code converts a hexadecimal string (a = "1a2b3c") into a bytes object (br) using list comprehension in a single line.

Python
a = "1a2b3c"
br = bytes([int(a[i:i+2], 16) for i in range(0, len(a), 2)])

print(type(a))   
print(br)       
print(type(br)) 

Output
<class 'str'>
b'\x1a+<'
<class 'bytes'>

Explanation:

  • The list comprehension [int(a[i:i+2], 16) for i in range(0, len(a), 2)] splits the string into 2-character chunks, converts each chunk from hexadecimal to decimal, and stores the results as a list of integers.
  • The bytes() function converts this list into a bytes object.

Related Articles:


Next Article

Similar Reads