Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `(33).to_bytes(2, 'big')` return `b'\x00!'` instead of `b'\x00\x21'`?

I'm having a problem converting int to bytes in Python.

This works -

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

However this does not work as I would expect -

>>> (33).to_bytes(2, 'big')
b'\x00!'

What am I not understanding?

like image 216
Julie Avatar asked Sep 21 '16 17:09

Julie


3 Answers

The decimal value 33 maps into the character ! by the ASCII standard, so the interpreter can show it without using escape codes:

>>> b'\x21' * 3
b'!!!'

When printing a bytes object, python treats it as a sequence of characters (every character is saved as a byte, with each byte using normally a memory of 8 bits that maps into 2 hexadecimal digits value, e.g. 0x21 => 0b 0010 0001 => 33), so values with corresponding printable ASCII characters are shown as their ASCII characters, and the rest are being represented by their hexadecimal values (in the format of \xDD).

like image 100
Uriel Avatar answered Nov 10 '22 15:11

Uriel


According to documentation -> https://docs.python.org/3.3/library/stdtypes.html

 >>> (1024).to_bytes(2, byteorder='big')
 b'\x04\x00'
 >>> (1024).to_bytes(10, byteorder='big')
 b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
 >>> (-1024).to_bytes(10, byteorder='big', signed=True)
 b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
 >>> x = 1000   
 >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')
 b'\xe8\x03'
like image 3
Sherzod Mamatov Avatar answered Nov 10 '22 15:11

Sherzod Mamatov


You're not understanding that ! is ASCII character 33, equivalent to \x21. This bytestring is exactly the bytestring you asked for; it just isn't displayed the way you were expecting.

like image 1
user2357112 supports Monica Avatar answered Nov 10 '22 14:11

user2357112 supports Monica