int.from_bytes() 字节串转整数
最后更新:2026-09-22
int.from_bytes() 字节串转整数
int.from_bytes(bytes, byteorder) 把字节串按指定字节序转成整数。
| 分类 | 数字类型方法 |
|---|---|
| 类型 | 内建类型方法 |
| Python 版本 | all |
📝 语法
int.from_bytes()
⚙️ 参数
| bytes 必选 | 要转换的字节串(bytes 或 bytearray)。 |
|---|---|
| byteorder 必选 | 字节序:'big' 高字节在前,'little' 低字节在前。 |
| signed 可选 | 是否按有符号数解释;为 True 时按补码解码。(默认值:False) |
返回值:int。按指定字节序转换出的整数。
是否修改原对象:否(返回新对象)
💥 异常
ValueError— byteorder 不是 'big'/'little' 时抛出。TypeError— bytes 不是字节类对象时抛出。
▶ 示例
编辑下方代码,点击运行,在输出面板查看结果:
运行结果:
255
255
💡 相关案例
更多实战案例即将上线,敬请期待。
❓ 常见问题
Qfrom_bytes() 是类方法吗?
A是,用 int.from_bytes(b, 'big') 直接调用,不需要实例。
Q参数有哪些?
A必填 bytes(bytes 或 bytearray)和 byteorder('big'/'little');signed=True 时按补码解码为负数。
Q和 to_bytes() 什么关系?
A互为逆运算:不溢出时 int.from_bytes(x.to_bytes(2, 'big'), 'big') 等于 x。
Q解析网络字节序数据怎么写?
A网络协议多用大端:int.from_bytes(data, 'big')。