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.

PythonData Integrity

Code

pythonsnippet
19 lines
# 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: 5

What 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

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`.