Hex String as Binary Data
To convert a hex string such as
'FF0001AF' to binary data, use the
binascii.unhexlify(hex_str) function that returns the binary data represented by the hexadecimal string.
Note that this converts two hex string digits to one byte, i.e., hex string
'F0' is converted to the byte representation
11110000, or in binary notation
Here’s an example:
import binascii hex_str = 'FF0001AF' bin_str = binascii.unhexlify(hex_str) print(bin_str) # b'\xff\x00\x01\xaf'
But what if you have given the hex string with whitespace separated notation so that each byte representation is separated by an empty space?
import binascii hex_str = 'FF 00 01 AF' bin_str = binascii.unhexlify(hex_str)
This will raise the following error message:
Traceback (most recent call last): File "C:\Users\...\code.py", line 4, in <module> bin_str = binascii.unhexlify(hex_str) binascii.Error: Odd-length string
You can fix this error by removing all empty spaces from the hex string using the
string.replace(' ','') method call.
import binascii hex_str = 'FF 00 01 AF' bin_str = binascii.unhexlify(hex_str.replace(' ', '')) print(bin_str) # b'\xff\x00\x01\xaf'
Write Hex String as Binary File
You can write the result of the hex string to binary conversion to a file by creating a file object using
open(filename, 'wb') and writing the binary string to a binary file using the
file_object.write(bin_str) function call. You obtain the binary string from the hex string using the
binascii.unhexlify(hex_string) function call.
Here’s the minimal example:
import binascii hex_str = 'FF0001AF' bin_str = binascii.unhexlify(hex_str) with open('hex_file.dat', 'wb') as f: f.write(bin_str)
The code snippet produces no standard output, but the new file
'hex_file.dat' is exactly how a file with random bytes is supposed to look: confusing! 😅
🌎 Recommended Tutorial: How to Write to a Binary File in Python?
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.