10/14/2007

Manipulate bits in C

1. Definition:
const int FIRST = 1 << 0;
const int SECOND = 1 << 1;
const int THIRD = 1 << 2;

Why defines the bit flag like this? Oh, just for clarity.

2. Setting bit flag:
int flags = 0;

flags |= FIRST;
flags |= SECOND;
flags |= THIRD;

if (flags & FIRST) {
printf("FIRST bit has been set.\n");
} else if (flags & SECOND) {
printf("SECOND bit has been set.\n");
}
...

3. Clearing bit flag:
flags &= ~FIRST;
flags &= ~SECOND;
...

No comments: