有没有Python模块可以帮助我将字符串转换为64位整数?(此字符串的最大长度为8个字符,因此应该适合长整型)。
我想避免编写自己的方法。
示例:
Input String Hex result (Base-10 Integer)
'Y' 59 89
'YZ' 59 5a 22874
...
有没有Python模块可以帮助我将字符串转换为64位整数?(此字符串的最大长度为8个字符,因此应该适合长整型)。
我想避免编写自己的方法。
示例:
Input String Hex result (Base-10 Integer)
'Y' 59 89
'YZ' 59 5a 22874
...
struct
的工作:>>> s = 'YZ'
>>> struct.unpack('>Q', '\x00' * (8 - len(s)) + s)
(22874,)
>>> int(s.encode('hex'), 16)
22874
我觉得没有内置的方法能够做到这一点,但是很容易自己想出一个方法:
>>> int("".join([hex(ord(x))[2:] for x in "YZ"]), 16)
22874
这个过程使用的是十六进制,当然可以进行优化。我会把这部分留作“练习”。
sum(ord(c) << i*8 for i, c in enumerate(mystr))
>>> reduce(lambda a,b: a*256+b, map(ord,'YZ'), 0)
22874
struct.pack('>H', 22874)
。 - Roman Bodnarchukhash(s)
)? - Anentropic