How to convert a string to a Base-10 view?

Is there any python module that will help me convert a string to a 64 bit integer? (The maximum length of this string is 8 characters, so it should match the length).

I would not want to write my own method.

Example:

Input String   Hex          result (Base-10 Integer)
'Y'            59           89
'YZ'           59 5a        22874
...
+5
source share
4 answers

This is a job for struct:

>>> s = 'YZ'
>>> struct.unpack('>Q', '\x00' * (8 - len(s)) + s)
(22874,)

Or a little more complicated:

>>> int(s.encode('hex'), 16)
22874
+7
source

I donโ€™t think there is a built-in method for this, but itโ€™s easy enough to prepare:

>>> int("".join([hex(ord(x))[2:] for x in "YZ"]), 16)
22874

This goes through base 16, which of course can be optimized. I will leave it an โ€œexerciseโ€.

+4
source

:

sum(ord(c) << i*8 for i, c in enumerate(mystr))
+3
>>> reduce(lambda a,b: a*256+b, map(ord,'YZ'), 0)
22874
+1