aeduG aeduG - 1 month ago 10
Python Question

Convert 16 bytes of random data to integer in Python

I have generated a random 16 byte string. It looks like this:

b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\'


I want to convert this to a (positive) integer. What's the best way to do this in Python?

I appreciate the help.

Answer

In Python 3.2+, you can use int.from_bytes():

>>> int.from_bytes(b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\', byteorder='little')
122926391642694380673571917327050487990

You can also use 'big' byteorder:

>>> int.from_bytes(b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\', byteorder='big')
242210931377951886843917078789492013660

You can also specify if you want to use two's complement representation. For more info: https://docs.python.org/3/library/stdtypes.html