首页 > 解决方案 > 函数 to_bytes 显示错误的输出

问题描述

Python3 函数 to_bytes 显示错误的输出

num = 9
num.to_bytes(4,'big')

输出

b'\x00\x00\x00\t'

预期产出

b'\x00\x00\x00\x09'

标签: python

解决方案


正如评论中提到的,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'

推荐阅读