How to Write a Hex String as Binary Data & Binary File in Python?

5/5 - (3 votes)

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 b'\xf0'.

binascii.unhexlify(hex_str)

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?