简体   繁体   中英

Check the bit settings with the bitwise operators

I have this source C:

#include <stdio.h>

#define BLUE 1
#define GREEN 2
#define RED 4

int main(void) {
    unsigned short i;
    char *array[8] = { "000", "001", "010", "011", "100", "101", "110", "111"};

    for(i = 0x0000; i <= 0x0007; i++) {
        printf("%d) %s -> ", i, array[i]);
        if(i & (BLUE | GREEN))
            printf("V\n");
        else
            printf("F\n");  
    }

    printf("\n\n");

    for(i = 0x0000; i <= 0x0007; i++) {
        printf("%d) %s -> ", i, array[i]);
        if(!((i | (BLUE)) ^ (i | (GREEN))))
            printf("V\n");
        else
            printf("F\n");  
    }

    return 0;
}

With the first FOR of the program I get the truth table on the behavior of the expression:

(i & (BLUE | GREEN))

That is, they are able to verify that at least one of the BLUE or GREEN bits (or both) are set to 1.

Now, I would like to check if both the BLUE and GREEN bits are at 1. I managed to do this with the expression:

(! ((i | (BLUE)) ^ (i | (GREEN)))))

But I don't like it at all! I thought I'd use a "~" instead of "!" but it does not work. Anyone have an idea how this can be done using only bitwise operators?

I would like to check if both the BLUE and GREEN bits are at 1.

(i & (BLUE|GREEN)) == (BLUE|GREEN)

Applying & to a combination of bits gives you the subset of those bits which were on. You know you can test for any of those by seeing if the result is zero (not all bits off). To test for all of them, just test that the result is the same as the combination of bits you just tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM