Thursday, October 29, 2009

Bit masking



As system, kernel and device driver programmer, you, of course use heavy of bitwise operation. This is a simple C code demonstrate bit masking and it's use in the real world ;), see also bit packing/unpacking for more fun.

#include <stdio.h>

enum
{
SANDRA = 1 << 0,
DESSY = 1 << 1,
YANA = 1 << 2,
SUSAN = 1 << 3
};


void
print(unsigned char val)
{

printf("val: %u\n", val);
printf("SANDRA loves me: %i\n", (val & SANDRA) ? 1 : 0);
printf("DESSY loves me: %i\n", (val & DESSY) ? 1 : 0);
printf("YANA loves me: %i\n", (val & YANA) ? 1 : 0);
printf("SUSAN loves me: %i\n", (val & SUSAN) ? 1 : 0);
}


int
main(void)
{

unsigned char
val = 0;
val = SANDRA | DESSY | YANA;
print(val);
printf("\n");
val &= ~SANDRA;
print(val);
printf("\n");
val &= ~(DESSY | YANA);
val |= (SUSAN | SANDRA);
print(val);
printf("\n");
val &= ~(SANDRA | DESSY | YANA | SUSAN);
print(val);
return
0;
}