Reputation: 717
I always get confused when I am about to use a bit map to store multiple flags. For example, if there are 10 possible properties for an object (all Yes or No), I use an unsigned int and the first 10 bits (from LSB) based on the properties. Now how to set and unset a particular bit and also how to check if a bit is set or not?
If I want to unset the 5th bit, I use: bitand (flag, 2^5 - 1)
But I am not clear on what to use to check if 5th bit is set or not.
Upvotes: 9
Views: 2437
Reputation: 100668
check if the nth bit is set:
(flags & (1 << n)) != 0
set the nth bit:
flags |= (1 << n)
clear the nth bit:
flags &= ~(1 << n)
toggle the nth bit:
flags ^= (1 << n)
Upvotes: 24