Startec
Startec

Reputation: 13206

Python 3 how to convert a large number expressed as bytes into an integer?

I have:

n = 257
a = n.to_bytes(2, 'little')
a = b'\x01\x01'

How can i convert this back into 257

Also, is there any way to show to_bytes without specifying how many bytes?

Upvotes: 2

Views: 135

Answers (1)

Navith
Navith

Reputation: 1069

Use the complementary int.from_bytes and specify the byteorder again.

>>> n = 257
>>> n_bytes = n.to_bytes(2, "little")
>>> n_again = int.from_bytes(n_bytes, "little")
>>> n_again == n
True

Upvotes: 3

Related Questions