binascii Module¶
The binascii module contains functions for converting between binary and ASCII representations, including hex encoding and uuencoding.
Complexity Reference¶
| Operation | Time | Space | Notes |
|---|---|---|---|
hexlify() |
O(n) | O(n) | n = input length |
unhexlify() |
O(n) | O(n) | n = hex length |
b2a_base64() |
O(n) | O(n) | Encode to base64 |
Binary-ASCII Conversions¶
Hex Encoding¶
import binascii
# Hex encode - O(n)
data = b'hello'
hex_str = binascii.hexlify(data)
print(hex_str) # b'68656c6c6f'
# Hex decode - O(n)
decoded = binascii.unhexlify(hex_str)
print(decoded) # b'hello'
Base64 Encoding¶
import binascii
# Encode - O(n)
data = b'binary data'
b64 = binascii.b2a_base64(data)
print(b64)
# Decode - O(n)
decoded = binascii.a2b_base64(b64)
print(decoded)