Home > database >  Mixing colors with bitfields in C with bitwise operators?
Mixing colors with bitfields in C with bitwise operators?

Time:02-01

I was reading the Wikipedia entry on bit-fields, and saw how one might use binary numbers to represent primary colors and combine them using bitwise OR (|) operators. I want to check if one color is contained in another.

#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;
}

I understand why this happens but is there is a bitwise operation or combination thereof that achieves the result I want ?

CodePudding user response:

If you want to check if all primary colors of a given color a are also part of another color b you could do it with a function like this (and as @Andrew Henle correctly mentioned, better use unsigned types for bit fields):

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

and use it like that

unsigned magenta = MAGENTA;
unsigned blue = BLUE;

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