C - Using Bitwise Operators to check mask flag


You can define masks with the following statements:

unsigned int male       = 0x1;         // Mask selecting first (rightmost) bit
unsigned int developer     = 0x2;         // Mask selecting second bit
unsigned int tester     = 0x4;         // Mask selecting third bit
unsigned int coder    = 0x8;         // Mask selecting fourth bit
unsigned int manager    = 0x10;        // Mask selecting fifth bit

In each case, a 1 bit will indicate that the particular condition is true.

These masks in binary each pick out an individual bit.

You can have an unsigned int variable, personal_data, which would store five items of information about a person.

If the first bit is 1, the person is male, and if the first bit is 0, the person is female.

If the second bit is 1, the person is developer.

if(personal_data & tester){
  /* tester */

You can use the OR operator to set individual bits in a variable using the mask.

To set personal_data to record a person as developer:

personal_data = personal_data|developer;  // Set second bit to 1

The second bit from the right in personal_data will be set to 1, and all the other bits will remain as they were.

You can set multiple bits in a single statement:

personal_data |= developer | tester | male;

To change the male bit to female, use the ~ operator with the bitwise AND:

personal_data &= ~male;                // Reset male to female

Related Topic