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.

PythonData Integrity

Code

pythonsnippet
23 lines
# 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 convert

How 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

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