aeduG aeduG - 1 year ago 129
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 Source

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')

You can also use 'big' byteorder:

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

You can also specify if you want to use two's complement representation. For more info:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download