问题
Is there any python module that would help me to convert a string into a 64-bit integer? (the maximum length of this string is 8 chars, so it should fit in a long).
I would like to avoid having to write my own method.
Example:
Input String Hex result (Base-10 Integer)
'Y' 59 89
'YZ' 59 5a 22874
...
回答1:
This is a job for struct:
>>> s = 'YZ'
>>> struct.unpack('>Q', '\x00' * (8 - len(s)) + s)
(22874,)
Or a bit trickier:
>>> int(s.encode('hex'), 16)
22874
回答2:
I don't think there's a built-in method to do this, but it's easy enough to cook up:
>>> int("".join([hex(ord(x))[2:] for x in "YZ"]), 16)
22874
This goes via base 16 which can of course be optimized out. I'll leave that "as an exercise".
回答3:
Another way:
sum(ord(c) << i*8 for i, c in enumerate(mystr))
回答4:
>>> reduce(lambda a,b: a*256+b, map(ord,'YZ'), 0)
22874
来源:https://stackoverflow.com/questions/10716796/how-to-convert-a-string-to-its-base-10-representation