Python Basics: Display Grouped Hex and Incremental CRC Values
Binary diagnostics benefit from readable hex groups and a repeatable checksum. binascii provides both without pretending that a checksum authenticates its input.
Prepare a scratch directory
Tested on Linux with CPython 3.12.14. You need Bash, a text editor, the named runtime, and standard mktemp, rm, and rmdir utilities. Run Python without -O so assertions remain enabled. The examples use only controlled local data; generated fixture directories are cleaned automatically.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save this as demonstrate-binascii.py:
import binascii
payload = b"123456789"
grouped = binascii.hexlify(payload, b":", -3)
print("Grouped hex:", grouped.decode("ascii"))
restored = binascii.unhexlify(grouped.replace(b":", b""))
assert restored == payload
whole = binascii.crc32(payload)
partial = binascii.crc32(payload[:4])
partial = binascii.crc32(payload[4:], partial)
assert whole == partial == 0xCBF43926
print(f"CRC-32: {whole:08x}")
print("Chunked checksum matches:", partial == whole)
try:
binascii.unhexlify(b"abc")
except binascii.Error:
print("Odd-length hex: rejected")
else:
raise AssertionError("Malformed hex was accepted")Run it:
python3 -B demonstrate-binascii.pyObserved output:
Grouped hex: 313233:343536:373839
CRC-32: cbf43926
Chunked checksum matches: True
Odd-length hex: rejectedRead the result
Negative bytes_per_sep groups from the left. The separators are a display choice, so the example removes them before unhexlify. Passing the first CRC result into the second call produces the same value as processing all bytes together.
Apply it carefully
CRC-32 detects many accidental errors but cannot establish authenticity against a malicious sender. Hex conversion is encoding, not encryption. Decide whether to accept separators in an input format rather than silently stripping arbitrary characters.
The official reference describes the behavior and options. These checks cover the fixture above rather than every input or platform.
Clean up
Remove the saved source, return to the starting directory, then remove the empty practice directory:
rm -- demonstrate-binascii.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirIf the directory is not empty, inspect its remaining contents rather than deleting unknown files.
Acknowledgements
This post was created with assistance from AI.