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?
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).
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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With