13

I got a problem I was hoping someone could help me figure out!

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

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

All combinations with those are possible. i.e., 0x01010000 = apple & orange

How can I from my string determine what fruit it is? I made a dictionary with all the combinations and then comparing to that, and it works! But I am wondering about a nicer way of doing it.

3 Answers 3

21

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

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

Now, you have a standard integer representing a bitset. use &, | and any other bitwise operator to test individual bits.

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

Now, if you need to convert back to your string:

>>> hex(value)
'0x1000100'
Sign up to request clarification or add additional context in comments.

2 Comments

It's called Bitwise Ops, and you can OR values together for combined results. The test, ((64|80) = 80) will return true if 64 (apple) is OR'ed into 80 (the sum of all OR values). wiki.python.org/moin/BitwiseOperators and
Thanks all for quick answers! I will read up on bitwise operators!
2

You could first of all convert your string to an integer:

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

then, you could set up a list for the fruits:

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

for determing what fruits you have that is enough:

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 output here is:

The fruit 'apple' is contained in '0x01010000'
The fruit 'orange' is contained in '0x01010000'

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.