Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python return unexpected characters from the to_bytes() method?

Why do some of the integers passed to the to_bytes() method give 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 the 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'

I am using Python 3.6.4.

like image 931
Bartek Balcerzak Avatar asked Apr 22 '26 00:04

Bartek Balcerzak


1 Answers

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'
like image 157
Robᵩ Avatar answered Apr 23 '26 15:04

Robᵩ