سؤال

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
...
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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".

Another way:

sum(ord(c) << i*8 for i, c in enumerate(mystr))
>>> reduce(lambda a,b: a*256+b, map(ord,'YZ'), 0)
22874
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top