Convert Hex String to Bytes in Python
Converting a hexadecimal string to bytes in Python involves interpreting each pair of hexadecimal characters as a byte. For example, the hex string 0xABCD would be represented as two bytes: 0xAB and 0xCD. Let’s explore a few techniques to convert a hex string to bytes.
Using bytes.fromhex()
bytes.fromhex() method converts a hexadecimal string directly into an immutable bytes object.
a = "1a2b3c"
b = bytes.fromhex(a)
print(type(a))
print(type(b),b)
Output
<class 'str'> <class 'bytes'> b'\x1a+<'
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()
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.
a = "1a2b3c"
b = bytearray.fromhex(a)
print(type(a))
print(type(b),b)
Output
<class 'str'> <class 'bytearray'> bytearray(b'\x1a+<')
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()
binascii.unhexlify() converts a hexadecimal string to its byte equivalent, similar to bytes.fromhex(). The key difference is that unhexlify() is part of the binascii module, which handles binary and ASCII encoding/decoding, making it useful for working with formats like base64.
import binascii
a = "1a2b3c"
b = binascii.unhexlify(a)
print(type(a))
print(type(b),b)
Output
<class 'str'> <class 'bytes'> b'\x1a+<'
Explanation: This code uses the `binascii` module to convert the hex string "1a2b3c" to bytes using the `unhexlify()` function.
Using List Comprehension
You can convert a hexadecimal string into bytes using list comprehension in a single line by splitting the hex string into pairs of characters, converting each pair to its decimal equivalent and then converting the result into a bytes object.
a = "1a2b3c"
b = bytes([int(a[i:i+2], 16) for i in range(0, len(a), 2)])
print(type(a))
print(type(b),b)
Output
<class 'str'> <class 'bytes'> b'\x1a+<'
Explanation:
- List comprehension iterates through the string in 2-character chunks, converts each to decimal using int(a[i:i+2], 16), and stores the results as integers.
- bytes() function converts this list into a bytes object, stored in b.