我遇到了一个问题,希望有人能帮我解决!
我有一个包含十六进制数的字符串,等于'0x00000000'
,它代表:
0x01000000 = apple
0x00010000 = orange
0x00000100 = banana
所有这些都可以进行组合。即,0x01010000 = apple & orange
我如何从我的字符串中确定它是哪种水果?我制作了一个包含所有组合的字典,并将其与之比较,这样做可行!但我想知道更好的方法。
使用内置函数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'
首先,您可以将字符串转换为整数:
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'
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))