简体   繁体   English

使用按位运算符检查位设置

[英]Check the bit settings with the bitwise operators

I have this source C:我有这个源 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:通过程序的第一个 FOR,我得到了关于表达式行为的真值表:

(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.也就是说,他们能够验证 BLUE 或 GREEN 位(或两者)中的至少一个是否设置为 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:现在,我想检查 BLUE 和 GREEN 位是否都为 1。我设法用表达式做到了这一点:

(! ((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.我想检查蓝色和绿色位是否都为 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.要测试所有这些,只需测试结果与您刚刚测试的位组合相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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