Using Bitwise Operators to mask flags - C Operator

C examples for Operator:Bit Operator

Introduction

You can use the & operator to select a part of an integer variable or even just a single bit.

You first define a value, usually called a mask.

You can then AND this mask with the value that you want to select from.

unsigned int male       = 0x1;         // Mask selecting first (rightmost) bit
unsigned int french     = 0x2;         // Mask selecting second bit
unsigned int german     = 0x4;         // Mask selecting third bit
unsigned int italian    = 0x8;         // Mask selecting fourth bit
unsigned int american   = 0x10;        // Mask selecting fifth bit

You could test the variable, personal_data, for a German speaker with the following statement:

Demo Code

#include <stdio.h> 

int main(void) { 
    /* www  .  ja va  2s . c o  m*/
    unsigned int male       = 0x1;         // Mask selecting first (rightmost) bit
    unsigned int french     = 0x2;         // Mask selecting second bit
    unsigned int german     = 0x4;         // Mask selecting third bit
    unsigned int italian    = 0x8;         // Mask selecting fourth bit
    unsigned int american   = 0x10;        // Mask selecting fifth bit
    
    int personal_data = 10;
    
    if(personal_data & german)
      printf(" german ");
    
    if(!(personal_data & male) && ((personal_data & french) || (personal_data & italian)))
       printf(" male, french, italian");
    return 0; 
}

Result


Related Tutorials