是否有任何python模塊可以幫助我將字符串轉換爲64位整數? (這個字符串的最大長度是8個字符,所以它應該很長)。如何將字符串轉換爲其Base-10表示形式?
我想避免寫我自己的方法。
例子:
Input String Hex result (Base-10 Integer)
'Y' 59 89
'YZ' 59 5a 22874
...
是否有任何python模塊可以幫助我將字符串轉換爲64位整數? (這個字符串的最大長度是8個字符,所以它應該很長)。如何將字符串轉換爲其Base-10表示形式?
我想避免寫我自己的方法。
例子:
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
這通過基座16進入其能當然會被優化出來。我會留下這個「作爲一個練習」。
看看 '十六進制' 編碼:) –
>>> reduce(lambda a,b: a*256+b, map(ord,'YZ'), 0)
22874
另一種方式:
sum(ord(c) << i*8 for i, c in enumerate(mystr))
+1偉大的解決方案! – jamylak
'int(s.encode('hex'),16)', 完美,謝謝@羅曼 –
太棒了!有沒有簡單的方法來執行相反的轉換,即從整數22874獲得字符串'YZ'? –