Python hexadecimal comparison

Hey guys, I have a problem, I was hoping someone would help me figure it out!

I have a string with a hexadecimal number = '0x00000000', which means:

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

All combinations with them are possible. those.0x01010000 = apple & orange

How can I determine what kind of fruit is from my line? I made a dictionary with all the combinations, and then compared it with it, and it works! But I wonder how best to do this.

+5
source share
3 answers

Convert your string to an integer using the built-in function int()and specifying the base:

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

:

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'
+2
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))
0
source

All Articles