#194 – Storing a Set of Boolean Values as Bits
December 28, 2010 2 Comments
You might want to store a set of boolean values in a single variable. For example, you could keep track of a person’s talents, recording which talents each person has.
E.g.:
- Fred: good at Singing, Dancing
- Sally: good at Dancing, Juggling
- Ernie: good at Juggling, Joke-Telling, Singing
One way to store this information is to represent each talent with a single bit in a larger word and to then use the entire word to represent a person’s talents. A bit value of 1 indicates that the person has the talent and 0 indicates that they do not have the talent. Each person can have 0 or more talents.
For example, we could store information about four talents using four bits:
- Bit 0 (rightmost) – Singing
- Bit 1 – Dancing
- Bit 2 – Juggling
- Bit 3 (leftmost) = Joke-Telling
Here are the bit patterns for the sets of talents listed above (each word is 4 bits):
- 0 0 1 1 = Dancing + Singing (Fred)
- 0 1 1 0 = Juggling + Dancing (Sally)
- 1 1 0 1 = Joke-Telling + Juggling + Singing (Ernie)
You could just use an enum to do exactly this.
[Flags]
enum Talents
{
None = 0,
Dancing=1 ,
Juggling=2,
JokeTelling=4,
}
Talents SeansTalents = Talents.Dancing | Talents.JokeTelling;
if((SeansTalents & Talents.JokeTelling) == Talents.JokeTelling)
{
Console.WriteLine(“You’re a funny guy!”);
}
Yes, you certainly can. You’re ahead of me a bit, since that’s the topic of the next post, which will come out tomorrow morning. I wanted to start with a post that explained the underlying concept of using bits as flags.