int.to_bytes() 整数转字节串
最后更新:2026-09-22
int.to_bytes() 整数转字节串
int.to_bytes(length, byteorder) 把整数转成指定长度的字节串;byteorder 取 'big' 或 'little'。
| 分类 | 数字类型方法 |
|---|---|
| 类型 | 内建类型方法 |
| Python 版本 | all |
📝 语法
int.to_bytes()
⚙️ 参数
| length 必选 | 目标字节串的长度。 |
|---|---|
| byteorder 必选 | 字节序:'big' 高字节在前,'little' 低字节在前。 |
| signed 可选 | 是否按有符号数解释;为 True 时负数也能转换。(默认值:False) |
返回值:bytes。按指定长度和字节序转换出的字节串。
是否修改原对象:否(返回新对象)
💥 异常
OverflowError— 整数无法在 length 个字节内表示时抛出。ValueError— byteorder 不是 'big'/'little',或 signed 为 True 且整数为负时抛出。
▶ 示例
编辑下方代码,点击运行,在输出面板查看结果:
运行结果:
b'\x00\xff'
b'\xff\x00'
💡 相关案例
更多实战案例即将上线,敬请期待。
❓ 常见问题
Qto_bytes() 有哪些参数?
Alength(字节数)和 byteorder('big' 高字节在前 / 'little' 低字节在前)都是必填的;signed 可选,默认 False。
Qlength 不够用会怎样?
A抛 OverflowError: int too big to convert。
Q负数能转换吗?
A默认不能(抛 OverflowError),需要 signed=True 按补码转换:(-1).to_bytes(2, 'big', signed=True) 得到 b'\xff\xff'。
Qbyteorder 写错会怎样?
A抛 ValueError,只接受 'big' 和 'little'。