int.to_bytes Serializes Fixed Width
int.to_bytes serializes integers at a fixed width and byte order, from_bytes parses them back, and widths too small raise OverflowError instead of truncating.
Code
# to_bytes 按指定宽度与字节序序列化整数:定长字段的基础
value = 4660 # 0x1234
big = value.to_bytes(2, 'big')
little = value.to_bytes(2, 'little')
print('big :', list(big))
print('little:', list(little))
# from_bytes 用同样的字节序解析回来,往返无损
print('roundtrip big :', int.from_bytes(big, 'big') == value)
print('roundtrip little:', int.from_bytes(little, 'little') == value)
# 同一数值两种字节序字节不同:解析时字节序必须配对
print('different bytes :', big != little)
# signed=True 允许负数:同样宽度,补码表示
neg = (-1).to_bytes(2, 'big', signed=True)
print('neg :', list(neg), int.from_bytes(neg, 'big', signed=True))
# 宽度不够装下就抛 OverflowError,宁可失败也不静默截断
try:
(65536).to_bytes(2, 'big')
except OverflowError as exc:
print('overflow:', exc)Output
Captured from a sandboxed run of this snippet in the build pipeline.
big : [18, 52]
little: [52, 18]
roundtrip big : True
roundtrip little: True
different bytes : True
neg : [255, 255] -1
overflow: int too big to convertHow the snippet works
Top-level bindings value, big, little, neg hold the demo state — nothing sits inside a function scope.
Using it
The demo output is labeled (little:, roundtrip little:, different bytes :), so every printed line maps back to its originating operation.
Key statements
except OverflowError as exc:
print('overflow:', exc)
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `value`, `big`, `little`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.