Bit-bit calculation and detection

In some code I'm working on, I have to take care of ten independent parameters that can take one of two values ​​(0 or 1). This creates 2 ^ 10 different conditions. Some of the conditions are never met and can be omitted, but those that do occur are still LOTS and make switchall cases insane.

I want to use 10 operators ifinstead of huge switch. For this, I know that I have to use flag bits, or rather flags, since the language is javascript and it is easier to work with a 10-byte string with a representation of a 10-bit binary.

Now, my problem is that I do not know how to implement this. I saw that it was used in APIwhere multiple-choice variants are displayed with numbers 1, 2, 4, 8, ..., n ^ (n-1), which are the decimal equivalents of 1, 10, 100, 1000, and t .d. in binary format. Therefore, if we make a type call bar = foo(7), bar will be an object with any parameters that are allowed by the three right-most flags.

I can convert the decimal to binary and to each operator check ifto see if the corresponding digit is set. But I am wondering if there is a way to determine the n-thdecimal digit number, zero or one in binary form, without actually performing the conversion?

+5
source share
3 answers

Just use bitwise and. In C / C ++, it will be:

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

To ensure good performance, use symbolic names for flag masks instead of magic numbers, 1, 2, 4, 8, etc.

If the flags are somewhat homogeneous (for example, they represent ten spatial dimensions in some geometry problem), and the code for handling 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.
    }
}
+6
source

You can use 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
+2
source

You can get the number where the nth bit is set, and AND with your number. If the result is zero, your number does not have a bit set. Otherwise. Look here , too.

+1
source

All Articles