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.

4
  • What's its intended endianness? Commented Oct 23, 2016 at 21:02
  • Possibly related: stackoverflow.com/questions/444591/… Commented Oct 23, 2016 at 21:04
  • @Logan I saw that post too, but I don't understand why to use struct? That can't be the solution. Commented Oct 23, 2016 at 21:06
  • @kindall Little Endian Commented Oct 23, 2016 at 21:10

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
What is the command to go back to the original string from that number?
Looks like you could use int.to_bytes(): docs.python.org/3/library/stdtypes.html#int.to_bytes
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.