How to convert a string to its Base-10 representation?

ぃ、小莉子 提交于 2019-12-10 15:29:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!