有人可以向我解释为什么传递给 to_bytes() 方法的某些整数给出了奇怪的结果吗?
>>> b = 5152
>>> b.to_bytes(2, byteorder='big')
b'\x14 '
>>> b = 5153
>>> b.to_bytes(2, byteorder='big')
b'\x14!'
>>> b=16592
>>> b.to_bytes(2, byteorder='big')
b'@\xd0'
如何解释'@' '!' ' '?对于 16592,我期望 b'\x40\xd0'。
我阅读了 Python 3 文档,那里的所有示例都运行良好。 Python 3 to_byte() description .
>>> b=1024
>>> b.to_bytes(2, byteorder='big')
b'\x04\x00'
我还尝试了 this Stackoverflow post 的示例它就像一个魅力。
>>> b = 1245427
>>> b.to_bytes(3, byteorder='big')
b'\x13\x00\xf3'
附加信息:
Python 3.6.4 (default, Feb 1 2018, 11:06:09)
[GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux
程序在 Fedora 27 上运行。
最佳答案
如果解释为 ASCII 的字节值是可打印的,则该字节的 repr()
是可打印字符。
由于@
的ASCII值为0x40,这两个值等价于b'@'
, b'\x40'
。
通过演示比解释更容易理解:
>>> b'\x40'
b'@'
但是无论表示形式如何,该对象都是长度为 1 的 bytes
,第一个字节的值为 64:
>>> b'\x40'[0] == 64
True
>>> b'@'[0] == 64
True
回到你的例子,如果你想知道每个字节的十六进制值,你可以使用bytes.hex()
:
>>> b=16592
>>> b.to_bytes(2, byteorder='big').hex()
'40d0'
关于python - 为什么 Python 3.6.4 从 to_bytes() 方法返回意外字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49169356/