简体   繁体   English

为什么Python 3.6.4从to_bytes()方法返回意外字符?

[英]Why Python 3.6.4 returns unexpected characters from to_bytes() method?

could someone explain to me why some of the integers passed to to_bytes() method gives a strange result? 有人可以向我解释为什么传递给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'

How to interpret '@' '!' 如何解释'@''!' ' '? ''? For 16592 I expected b'\\x40\\xd0'. 对于16592,我期望b'\\ x40 \\ xd0'。

I read Python 3 documentation and all examples from there work fine. 我阅读了Python 3文档,并且那里的所有示例都能正常工作。 Python 3 to_byte() description . Python 3 to_byte()描述

>>> b=1024
>>> b.to_bytes(2, byteorder='big')
b'\x04\x00'

I also try an example for this Stackoverflow post and it works like a charm. 我还尝试了这个Stackoverflow帖子的示例,它的工作原理很吸引人。

>>> b = 1245427
>>> b.to_bytes(3, byteorder='big')
b'\x13\x00\xf3'

Aditional info: 附加信息:

Python 3.6.4 (default, Feb  1 2018, 11:06:09) 
[GCC 7.2.1 20170915 (Red Hat 7.2.1-2)] on linux

Program runs on Fedora 27. 程序在Fedora 27上运行。

If the value of a byte, interpreted as ASCII, is printable, then the repr() of that byte is the printable character. 如果解释为ASCII的字节值是可打印的,则该字节的repr()是可打印的字符。

Since the ASCII value of @ is 0x40, these two values are equivalent b'@' , b'\\x40' . 由于@的ASCII值为0x40,因此这两个值等效为b'@'b'\\x40'

This may be more easily seen through demonstration than an explanation: 通过演示可能比解释更容易看到:

>>> b'\x40'
b'@'

But regardless of representation, that object is a bytes of length 1, with a value of 64 in the first byte: 但是无论表示形式如何,该对象都是一个长度为1的bytes ,第一个bytes的值为64:

>>> b'\x40'[0] == 64
True
>>> b'@'[0] == 64
True

Returning to your example, if you want to know the hex value of each byte, you can use bytes.hex() : 回到您的示例,如果您想知道每个字节的十六进制值,则可以使用bytes.hex()

>>> b=16592
>>> b.to_bytes(2, byteorder='big').hex()
'40d0'

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

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