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 API
s 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?
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.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With