简体   繁体   English

Python 返回的 to_bytes 不符合预期

[英]Python return for to_bytes not as expected

(1112).to_bytes(8, 'big') (1112).to_bytes(8, '大')

Return:
# b'\x00\x00\x00\x00\x00\x00\x04X'

Expected:
# b'\x00\x00\x00\x00\x00\x00\x04\x58'

If I convert back from如果我从

# b'\x00\x00\x00\x00\x00\x00\x04X'

then the result is still 1112. Is this just a print issue with encoding?那么结果仍然是1112。这只是编码的打印问题吗?

This is normal behavior for bytes strings.这是bytes字符串的正常行为。 Their printable representations show ASCII characters if possible, the hex values otherwise.如果可能,它们的可打印表示会显示 ASCII 字符,否则显示十六进制值。 As an example to show the expected value is still there:作为显示预期值仍然存在的示例:

>>> a = (1112).to_bytes(8, 'big')
>>> a
b'\x00\x00\x00\x00\x00\x00\x04X'
>>> hex(a[7])
'0x58'
>>> chr(a[7])
'X'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM