【问题标题】:Mixing colors with bitfields in C with bitwise operators?使用按位运算符在 C 中将颜色与位域混合?
【发布时间】:2023-01-31 21:09:07
【问题描述】:

我正在阅读关于 bit-fields 的 Wikipedia 条目,了解如何使用二进制数来表示原色并使用按位或 (|) 运算符组合它们。我想检查一种颜色是否包含在另一种颜色中。

#include <stdio.h>

// primary colors
#define RED 0b001
#define GREEN 0b010
#define BLUE 0b100

// mixed colors 
#define BLACK 0b000
#define YELLOW (RED | GREEN)
#define MAGENTA (RED | BLUE)
#define CYAN (BLUE | GREEN)
#define WHITE (RED | GREEN | BLUE)

int main(void) 
{
    int magenta = MAGENTA;
    int blue = BLUE;

#define in &  // check if a color A is contained in another color B:
    printf("%s\n", blue in magenta ? "true" : "false"); // true
    printf("%s\n", magenta in blue ? "true" : "false"); // should be false but is true.
    return 0;
}

我明白为什么会这样,但是是否有按位运算或其组合可以达到我想要的结果?

【问题讨论】:

  • (magenta &amp; blue) == magenta
  • 您正在将 &amp; 更改为 in 以使其看起来更像自然语言。同时,&amp; 运算符并不关心左右参数的顺序。它只是检查这些位是否已设置。
  • @500-InternalServerError:不,不是。
  • 但是 &amp; 是对称的。所以 A & B == B & A。将 &amp; 细化为看起来像“in”中的不对称关系,你已经把自己弄糊涂了。

标签: c bit-manipulation bitwise-operators bit-fields


【解决方案1】:

如果你想检查给定颜色 a 的所有原色是否也是另一种颜色 b 的一部分,你可以使用这样的函数来完成:

int contains( int b, int a )  // returns != 0 if all primary colors of a are also part of b
{
  return ( b & a ) == a;
}

并像那样使用它

printf("%s
", contains( magenta, blue ) ? "true" : "false"); // true
printf("%s
", contains( blue, magenta ) ? "true" : "false"); // false

【讨论】:

  • 使用unsigned int进行按位运算比int好得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
相关资源
最近更新 更多