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

6
  • 90 (or 5A) -> Z, 33 -> !, 76 -> L - that's all just ASCII. That's what it shows for printable characters Commented Jun 2, 2022 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. Commented Jun 2, 2022 at 10:12
  • Do the answers to this question help at all? You could try: print(x.to_bytes(4, 'big').hex()) etc Commented Jun 2, 2022 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. Commented Jun 2, 2022 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 Commented Jun 2, 2022 at 11:41

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.