BlackWaspTM
.NET Framework
.NET 1.1+

Bit Manipulation with the BitArray (2)

The forty-second part of the C# Fundamentals tutorial examines the use of the BitArray class. This type of collection can be used to hold very large series of bits that can be manipulated either independently or collectively as an entire group.

Reading and Writing BitArray Contents

Reading Individual Bits

Single bits can be extracted from a BitArray using an index number appended to the collection name within square brackets. The class also provides a Get method that accepts the index as a parameter and returns the value of the bit at the specified position. Each method is demonstrated below:

BitArray flags = new BitArray(new bool[] { true, false, false, true });

Console.WriteLine(flags[0]);                // Outputs "True"
Console.WriteLine(flags.Get(1));            // Outputs "False"

Writing Individual Bits

You can set and clear individual bits in a BitArray. As with reading the individual bits, there are two ways to do so. Firstly, the index value may be appended to the collection name and the value of a bit assigned directly. Secondly, you can use the Set method. This method accepts an integer parameter for the index of the item to change and a Boolean indicating the new value. The following example shows both methods:

BitArray flags = new BitArray(16, false);

flags[0] = true;
flags.Set(1, true);

Writing Multiple Bits

Often you will want to set or clear all of the bits within a BitArray. This can be achieved using the SetAll method. The method requires one argument containing the new value for every bit within the collection.

BitArray flags = new BitArray(16);

flags.SetAll(true);

BitArray Length

As the BitArray class implements ICollection, it includes the Count property that returns the number of bits in the collection. In addition to this read-only property, BitArray provides a Length property that can be used to both request the number of items in the collection and to change the length.

When the Length property is set, the size of the BitArray may increase or decrease. If the new length is smaller than the existing number of items, the collection is truncated with all entries at indices equal to or higher than the new length being permanently erased. If the new length is larger than the current number of items then new items are appended to the BitArray. Each additional bit is initially false.

BitArray flags = new BitArray(new bool[] { true, false, false, true });

Console.WriteLine(flags.Count);             // Outputs 4
Console.WriteLine(flags.Length);            // Outputs 4
flags.Length = 8;
Console.WriteLine(flags.Length);            // Outputs 8
24 June 2007