2009-12-11 152 views
5

嗨,大家好,我遇到了一個問題,我希望有人能幫我弄明白!Python十六進制比較

我有一個十六進制數= '0x00000000'這意味着字符串:

0x01000000 = apple 
0x00010000 = orange 
0x00000100 = banana 

與所有組合都是可能的。即,0x01010000 = apple & orange

如何從我的字符串確定它是什麼水果?我製作了一本包含所有組合的字典,然後與之進行比較,並且工作正常!但我想知道更好的方法。

回答

11

轉換您的字符串爲整數,通過使用int()內置函數並指定一個基地:

>>> int('0x01010000',16) 
16842752 

現在,你必須代表一個bitset標準的整數。使用&,|和任何其他按位運算符來測試各個位。

>>> value = int('0x01010000',16) 
>>> apple = 0x01000000 
>>> orange = 0x00010000 
>>> banana = 0x00000100 
>>> bool(value & apple) # tests if apple is part of the value 
True 
>>> value |= banana  # adds the banana flag to the value 
>>> value &= ~orange # removes the orange flag from the value 

現在,如果你需要轉換回您的字符串:

>>> hex(value) 
'0x1000100' 
+0

這就是所謂的按位行動,你可以OR值一起合併後的結果。如果64(蘋果)被OR變爲80(所有OR值的總和),則測試((64 | 80)= 80)將返回真。 http://wiki.python.org/moin/BitwiseOperators和 – invert

+0

感謝KeyboardMonkey的鏈接。 –

+0

謝謝所有人的快速解答!我將閱讀按位運算符! – heffaklump

2

你可以首先所有的字符串轉換爲整數:

s = "0x01010000" 
i = int(s, 16) #i = 269484032 

然後,您可以設置列出水果名單:

fruits = [(0x01000000, "apple"), (0x00010000, "orange"), (0x00000100, "banana")] 

爲determing什麼水果你有足夠的:

s = "0x01010000" 
i = int(s, 16) 
for fid,fname in fruits: 
    if i&fid>0: 
     print "The fruit '%s' is contained in '%s'" % (fname, s) 

的輸出這裏是:

The fruit 'apple' is contained in '0x01010000' 
The fruit 'orange' is contained in '0x01010000' 
0
def WhichFruit(n): 
    if n & int('0x01000000',16): 
     print 'apple' 
    if n & int('0x00010000',16): 
     print 'orange' 
    if n & int('0x00000100',16): 
     print 'banana' 

WhichFruit(int('0x01010000',16))