简体   繁体   中英

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?

>>> 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'.

I read Python 3 documentation and all examples from there work fine. Python 3 to_byte() description .

>>> 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.

>>> 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.

If the value of a byte, interpreted as ASCII, is printable, then the repr() of that byte is the printable character.

Since the ASCII value of @ is 0x40, these two values are equivalent 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:

>>> 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() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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