python - 函数 to_bytes 显示错误的输出
问题描述
Python3 函数 to_bytes 显示错误的输出
num = 9
num.to_bytes(4,'big')
输出
b'\x00\x00\x00\t'
预期产出
b'\x00\x00\x00\x09'
解决方案
正如评论中提到的,int.to_bytes()
返回一个 ASCII 表示实现,您可以在CPython 的bytesobject.c
特别此处看到它的实现。
bytearray
如果您只想要数字,您可以使用 a或调用ord()
:
bytearray((9).to_bytes(4, byteorder="big"))[3]
9
或使用hex()
/ bytes.hex()
:
>>> [hex(item) for item in (9).to_bytes(4, byteorder="big")]
['0x0', '0x0', '0x0', '0x9']
>>> (9).to_bytes(4, byteorder="big").hex()
'00000009'
>>> (9).to_bytes(4, byteorder="big").hex(" ")
'00 00 00 09'
推荐阅读
- javascript - 用动画关闭 div
- python - 格式化与其他变量连接的列表的打印
- javascript - 在 Openlayer 中添加热键功能
- python - 查找行中第一个 NaN 值的索引
- android - 如何确保我的布局的所有部分都保持可见?
- windows - Bash 对 windows 的“for”
- google-app-engine - google-app-engine 脚本中的返回值始终为 None
- php - 如何将响应转换为适当的形式?
- security - 外部可访问的 Tomcat Manager 中的安全风险
- .net-core - 无法检测执行路径 Rider Dotnet 核心的 dbgshim 路径