bytes.hex Roundtrips Binary As Text
bytes.hex encodes binary as hex text with optional separators, and bytes.fromhex restores it, rejecting odd-length input instead of guessing.
Code
# bytes.hex() 把二进制编码成十六进制文本:日志、URL、配置里安全传输
payload = bytes([0x01, 0xCA, 0xFE, 0xBA, 0xBE])
encoded = payload.hex()
print(encoded)
# sep 参数每 N 字节插一个分隔符(3.8+)
print(payload.hex(":", 2))
# fromhex 是逆操作:空格忽略,奇数个十六进制字符直接报错
restored = bytes.fromhex("01 ca fe ba be")
print(restored == payload, len(restored))
try:
bytes.fromhex("abc")
except ValueError as err:
print("rejected:", err)
# 十六进制文本更长但零依赖、可肉眼比对
print("hex length:", len(encoded), "raw length:", len(payload))Output
Captured from a sandboxed run of this snippet in the build pipeline.
01cafebabe
01:cafe:babe
True 5
rejected: non-hexadecimal number found in fromhex() arg at position 3
hex length: 10 raw length: 5What the code does
Top-level bindings payload, encoded, restored hold the demo state — nothing sits inside a function scope.
Using it
Look for the rejected:, hex length: prefixes when the file runs; they tie each line to its step.
Key statements
except ValueError as err:
print("rejected:", err)
Interactive Tools for This Topic
Hex Dump ViewerPreview any text as a classic hexadecimal dump with byte offsets, sixteen bytes per row, and an ASCII column for quick inspection.Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.XOR Text EncoderXOR UTF-8 text bytes with a repeating key and output hex, with full decode back to the original text.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `payload`, `encoded`, `restored`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.