Python十六进制比较

12

我遇到了一个问题,希望有人能帮我解决!

我有一个包含十六进制数的字符串,等于'0x00000000',它代表:

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

所有这些都可以进行组合。即,0x01010000 = apple & orange

我如何从我的字符串中确定它是哪种水果?我制作了一个包含所有组合的字典,并将其与之比较,这样做可行!但我想知道更好的方法。

3个回答

21

使用内置函数int()并指定一个进制,将您的字符串转换为整数:

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

现在,你有一个表示位集合的标准整数。使用&|和任何其他位运算符来测试单个位。

>>> 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'

它被称为位运算符,您可以将值进行OR运算以获得组合结果。测试 ((64|80) = 80) 如果将64(苹果)OR运算到80(所有OR值的总和)中,则返回true。http://wiki.python.org/moin/BitwiseOperators - invert
谢谢大家的快速回答!我会学习位运算符的知识! - heffaklump

2

首先,您可以将字符串转换为整数:

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

然后,您可以为水果设置一个列表:
fruits = [(0x01000000, "apple"), (0x00010000, "orange"), (0x00000100, "banana")]

为了确定你拥有哪些水果,以下内容足够:
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))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接