实现说明
顶层就这几处状态:value、big、little、neg。
使用要点
- 直接运行文件,输出会带上标签,比如
little:、roundtrip little:、different bytes :——输出的每一行都能指回产生它的那次调用。
常见问题
这个示例需要哪些包?
一个都不用。代码用到的符号都在标准库里解析。 文件用顶层绑定保存自己的状态:value、big、little。
核心语句
except OverflowError as exc:
print('overflow:', exc)
代码示例
# 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)