user9993
user9993

Reputation: 6170

C# - Multidimensional BitArray

I'm attempting to use a multidimensional BitArray but I'm stuck with how to set or read bits with it.

With a normal one dimension BitArray I can simply do the following to set a bit:

bitArray.Set(0, true);

However I don't know how to do the same with a two-dimension bit array. For example the following code does not make sense, as the Set method requires an index but I've already supplied the index previously in the "[0, 0]":

    bitArray[0, 0].Set(0, true);

My question: What's the proper way of making and then using a multidimensional BitArray?

Upvotes: 1

Views: 4182

Answers (2)

antgraf
antgraf

Reputation: 184

public sealed class BitArray2D
{
    private BitArray _array;
    private int _dimension1;
    private int _dimension2;

    public BitArray2D(int dimension1, int dimension2)
    {
        _dimension1 = dimension1 > 0 ? dimension1 : throw new ArgumentOutOfRangeException(nameof(dimension1), dimension1, string.Empty);
        _dimension2 = dimension2 > 0 ? dimension2 : throw new ArgumentOutOfRangeException(nameof(dimension2), dimension2, string.Empty);
        _array = new BitArray(dimension1 * dimension2);
    }

    public bool Get(int x, int y) { CheckBounds(x, y); return _array[y * _dimension1 + x]; }
    public bool Set(int x, int y, bool val) { CheckBounds(x, y); return _array[y * _dimension1 + x] = val; }
    public bool this[int x, int y] { get { return Get(x, y); } set { Set(x, y, value); } }

    private void CheckBounds(int x, int y)
    {
        if (x < 0 || x >= _dimension1)
        {
            throw new IndexOutOfRangeException();
        }
        if (y < 0 || y >= _dimension2)
        {
            throw new IndexOutOfRangeException();
        }
    }
}

Upvotes: 1

Dai
Dai

Reputation: 155065

An instance of BitArray is not an array as far the CLR is concerned (that is, BitArray is not an "array type"). If you want to store 2-dimensional bit information you have a few options (all of my examples create a 10x20 2D volume):

a) Use a single array of BitArray like so:

// Init:
BitArray[] storage = new BitArray[ 20 ];
for(int y=0;y<storage.Length;y++) storage[y] = new BitArray( 10, true );

// Usage:
Boolean at5x7 = storage[7][5];

b) Use the BitArray as a 2D space in itself, by indexing by row-and-column (this will actually be faster as the CLR won't invoke its Bounds-checking as often):

// Init:
const Int32 width = 10, height = 20;
BitArray storage = new BitArray( width * height );

// Usage:
Boolean at5x7 = storage[ (5 * width) + 7];

Upvotes: 8

Related Questions