Data is often represented in hexadecimal format, which is a commonly used system for representing binary data in a human-readable form. In Python, the hex string is converted into bytes to work with binary data or to extract each value from the raw data. To convert the hex string into bytes, the bytes.from() and codecs.decode() functions are used.
This post provides various ways to convert hex string to bytes using the given below contents:
- Method 1: Using bytes.fromhex(hex_string)
- Method 2: Using codecs.decode() Function
- Method 3: Using the binascii Module
Method 1: Using bytes.fromhex(hex_string)
The “bytes.fromhex()” function is used to return a byte object (sequences of integers) by accepting the single hexadecimal value. The “bytes.fromhex(hex_string)” function is utilized in the following code to convert hex string to bytes:
Code:
hex_string = 'ff'
print('Hex String Value: ',hex_string)
output = bytes.fromhex(hex_string)
print('Bytes Value: ',output)
print(type(output))
In this example, the “bytes.fromhex()” function takes the hexadecimal strings “ff” as an argument and converts it into bytes object.
Output:
The given hex string has been converted into bytes.
Method 2: Using codecs.decode() Function
The “codecs.decode()” function is used to decode binary strings into normal form. In the below code the “codecs.decode()‘ function is used to convert hex string to bytes:
Code:
import codecs
bytes_value = codecs.decode('ff', 'hex_codec')
print(type(bytes_value))
print(bytes_value)
The “codecs.decode()” function converts the hex string into bytes by taking the hex string “ff” as a first argument and the encoding “hex_codec” as a second argument.
Output:
The given string has been converted into a bytes object.
Method 3: Using the binascii Module
In Python, the module named “binascii” is utilized to convert the binary representations into ASCII-encoded binary representations. The “binascii.unhexlify()” function of the binascii module is used in the below code to convert hex string to bytes:
Code:
import binascii
hexa_string = '507974686f6e'
bytes_value = binascii.unhexlify(hexa_string)
print('Byte value of the string:', bytes_value)
The “binascii.unhexlify()” function takes the “hex string” as an argument and converts them into bytes.
Output:
The input hex string “507974686f6e” has been converted into bytes “Python.”
Conclusion
To convert hex strings to bytes, the “bytes.fromhex()” and “codecs.decode()” functions are used. Apart from that, the “binascii” module is also exercised in Python. The “bytes.fromhex()” function takes the hex string as an argument and converts it into bytes. Similarly, the “codecs.decode()” function decodes the hex string into bytes, and the “unhexlify()” function can also return the bytes of the input hex string. This guide presented various ways to convert hex strings to bytes in Python.