0

I am working my way through bytes in python and I have to say I have come across numerous difficulties. One of them is int.tobytes() function. Converting integers up to 32 works fine, but after that the output has single characters that I don't understand. For example:

x=90
y=33
z=76

print(x.to_bytes(4, 'big'))
print(y.to_bytes(4, 'big'))
print(z.to_bytes(4, 'big'))

Output:
b'\x00\x00\x00Z'
b'\x00\x00\x00!'
b'\x00\x00\x00L'

I don't understand the single digit byte at the start. For example, I would expect 90 to be: '\x00\x00\x00\x5A'(Converting it to hexadecimal), but instead I get results like this. I can't seem to find solutions online. What do these single characters represent? Thanks

Jouenshin
  • 1
  • 2
  • 90 (or 5A) -> Z, 33 -> !, 76 -> L - that's all just _ASCII_. That's what it shows for [printable characters](https://en.wikipedia.org/wiki/ASCII#Printable_characters) – jonrsharpe Jun 02 '22 at 10:12
  • The output you posted is correct. When you say you want: `'\x00\x00\x00\x5A'`, that is exactly what python prints and is shown in your output. – quamrana Jun 02 '22 at 10:12
  • Do the answers to this [question](https://stackoverflow.com/questions/19210414/byte-array-to-hex-string) help at all? You could try: `print(x.to_bytes(4, 'big').hex())` etc – quamrana Jun 02 '22 at 10:14
  • @jonrsharpe Thanks for the answer. Understood, but why is ASCII used instead of utf-8? Why I use ```sys.getdefaultencoding()``` it shows 'utf-8. – Jouenshin Jun 02 '22 at 11:41
  • @quamrana Thanks for the answer. Using ```hex()``` I can easily see the output it hexadecimal and it matches the one I expected – Jouenshin Jun 02 '22 at 11:41
  • Because that's how bytes objects work. Read e.g. https://docs.python.org/3/library/stdtypes.html#binary-sequence-types-bytes-bytearray-memoryview. – jonrsharpe Jun 02 '22 at 11:52

0 Answers0