#983 – Using a BitArray to Store a Large Collection of Boolean Values

If you need to store a set of boolean values, you can store them in array of type bool.  Each element of the array would require 8 bits, despite storing a single boolean value.

You can more efficiently store a set of boolean values in an enum type, marking the type with the Flags attribute.  This allows storing a maximum of 32 distinct boolean values.

To store a larger collection of boolean values, you can use the BitArray type.  A BitArray allows you to index into an array of boolean values, but stores the values in a more compact form than would be used by a normal array.

Below, we use an enum to index into a 50-element BitArray.

        public enum States
        {
            Alabama,
            // ...
            Wyoming
        }

            BitArray baStatesIveVisited = new BitArray(50);

            baStatesIveVisited[(int)States.Minnesota] = true;
            baStatesIveVisited[(int)States.Wisconsin] = true;
            baStatesIveVisited[(int)States.California] = true;

            States nextState = States.Alabama;
            foreach (bool b in baStatesIveVisited)
                Console.WriteLine("{0}:{1}", nextState++, b);

983-001

Advertisement

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

One Response to #983 – Using a BitArray to Store a Large Collection of Boolean Values

  1. Pingback: Dew Drop – November 27, 2013 (#1673) | Morning Dew

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: