#194 – Storing a Set of Boolean Values as Bits

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)
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #194 – Storing a Set of Boolean Values as Bits

  1. odecey says:

    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!”);
    }

    • Sean says:

      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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: