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.
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.
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
A solution compatible both with Python 2 and Python 3 is to use struct.unpack:
import struct
n = b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\'
m = struct.unpack("<QQ", n)
res = (m[0] << 64) | m[1]
print(res)
Result: 298534947350364316483256053893818307030L