3

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.

awaelchli
  • 796
  • 7
  • 23

2 Answers2

5

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

Logan
  • 1,575
  • 1
  • 17
  • 26
  • Oh I think that's exactly what I need. If my data is random, I think it does not matter if I use little or big endian, it will just shuffle the number, right? – awaelchli Oct 23 '16 at 21:14
  • I guess it would depend on what exactly you're planning on doing with the integer, but yes, the number will be different if you change the byteorder. – Logan Oct 23 '16 at 21:16
  • What is the command to go back to the original string from that number? – awaelchli Oct 23 '16 at 21:18
  • Looks like you could use int.to_bytes(): https://docs.python.org/3/library/stdtypes.html#int.to_bytes – Logan Oct 23 '16 at 21:21
2

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

maki
  • 431
  • 3
  • 8