5

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
...
E.Z.
  • 6,393
  • 11
  • 42
  • 69

4 Answers4

9

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
Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
4

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

unwind
  • 391,730
  • 64
  • 469
  • 606
3

Another way:

sum(ord(c) << i*8 for i, c in enumerate(mystr))
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1
>>> reduce(lambda a,b: a*256+b, map(ord,'YZ'), 0)
22874
Dan D.
  • 73,243
  • 15
  • 104
  • 123