A Custom BitArray in C#

I haven’t worked with low level code recently and for some reason I decided to entertain myself this morning by looking at bit manipulation. The .NET Framework has a convenient BitArray class. I thought I’d implement a crude version from scratch just for fun. I made a custom TinyBitArray class that holds only 32 values. My demo calling program is:

TinyBitArray tba = new TinyBitArray();
tba.SetValue(0, true);
tba.SetValue(31, true);
tba.SetValue(15, true);
Console.WriteLine(tba.GetValue(31)); // ‘true’
Console.WriteLine(tba.GetValue(16)); // ‘false’

The main idea of a bit array is to have an array which holds one of two possible values. You can do this with a normal array of int (where the values are 0 or 1) or a normal array of bool (where the values are false or true) but this wastes a lot of space. So if an uint is 32 bits in size we can store up to 32 values. For example the integer value 13 = 00000000-00000000-00000000-00001101 represents an array with bits 0, 2, and 3 set. I use unsigned int so I can use bit 31 which is the sign bit in a regular int.

My code is below. To make a bit array which holds more than 32 values, instead of using a single uint you can have an array of uints. Then to make an index to the array you can compute row = index / 32 and col = index % 32. Well I entertained myself and if for some remote reason I ever need a custom bit array I can code it up pretty quickly.

class TinyBitArray
  private uint data;

  public TinyBitArray()
    this.data = 0;

  public void SetValue(int index, bool value)
    if (value == true) {
      uint mask = TwoToThePower(index); // all 0s except one 1
      this.data = this.data | mask;
    else {
      uint mask = uint.MaxValue – TwoToThePower(index);
      this.data = this.data & mask;

  public bool GetValue(int index)
    uint mask = TwoToThePower(index);
    if ((this.data & mask) == 0)
      return false;
      return true;

  private uint TwoToThePower(int n)
    uint result = 1;

    for (uint i = 0; i < n; ++i) { result = result * 2; }
    return result;
} // class TinyBitMatrix


This entry was posted in Software Test Automation. Bookmark the permalink.