views:

69

answers:

3

Hi all,

In some code I'm working on I should take care of ten independent parameters which can take one of two values (0 or 1). This creates 2^10 distinct conditions. Some of the conditions never occur and can be left out, but those which do occur are still A LOT and making a switch to handle all cases is insane.

I want to use 10 if statements instead of a huge switch. For this I know I should use flag bits, or rather flag bytes as the language is javascript and its easier to work with a 10 byte string with to represent a 10-bit binary.

Now, my problem is, I don't know how to implement this. I have seen this used in APIs where multiple-selectable options are exposed with numbers 1, 2, 4, 8, ... , n^(n-1) which are decimal equivalents of 1, 10, 100, 1000, etc. in binary. So if we make call like bar = foo(7), bar will be an object with whatever options the three rightmost flags enable.

I can convert the decimal number into binary and in each if statement check to see if the corresponding digit is set or not. But I wonder, is there a way to determine the n-th digit of a decimal number is zero or one in binary form, without actually doing the conversion?

+3  A: 

Just use a bitwise-and. In C/C++, this would be:

if (flags & 1) {
    // Bit zero is set.
}
if (flags & 2) {
    // Bit one is set.
}
if (flags & 4) {
    // Bit two is set.
}
...

For production goodness, use symbolic names for the flag masks instead of the magic numbers, 1, 2, 4, 8, etc.

If the flags are homogeneous in some way (e.g., they represent ten spatial dimensions in some geometry problem) and the code to handle each case is the same, you can use a loop:

for (int f = 0; f < 10; ++f) {
    if (flags & (1 << f)) {
        // Bit f is set.
    }
}
Marcelo Cantos
WOW! Very quick! I wanted to accept your answer right away, but apparently I should wait for at least 9 minutes. Thanks really.
Majid
+1 was typing something similar but you was faster ;)
RC
+1  A: 

You could get a number that has the n-th bit set and AND it with your number. If the result is zero your number didn't have the bit set. Otherwise, it did. Look here, also.

nc3b
+1  A: 

You can use a bitwise and:

10 & 2^1 is true because 10 = 1010b 
                                ^ 1
 8 & 2^1 is false because 8 = 1000b 
                                ^ 0
10 & 2^3 is true because 10 = 1010b 
                              ^ 1
RC