dividing system.collections.bitarray into sub bitarrays of 32 bits each

I have searched in net but not getting exactly what I need. I have a bitarray of size 15,936. I need to divide this bit array into list of bitarrays , with each bit array having 32 bits(15936/32 = 498 bitarray list).

Not able to find exactly how to divide bitarray. Please do help.

Thanks,

Jon Skeet
people
quotationmark

The first that you want 32-bit values makes this pretty easy, because you can copy it to an int[], then create one BitArray per int, passing the data by creating a single-element int array:

int[] values = new int[bigBitArray.Length / 32];
bigBitArray.CopyTo(values, 0);
var smallBitArrays = values.Select(v => new BitArray(new[] { v })).ToList();

Or more efficiently, reusing the same int[] for each iteration:

int[] values = new int[bigBitArray.Length / 32];
bigBitArray.CopyTo(values, 0);
// Reuse this on every iteration, to avoid creating more arrays than we need.
// Somewhat ugly, but more efficient.
int[] buffer = new int[1];
var smallBitArrays = values.Select(v =>
{ 
    buffer[0] = v; 
    return new BitArray(buffer))
}).ToList();

If those give you the bit arrays in the opposite order to what you expect, just call Array.Reverse(values) after the CopyTo call.

It's a pity that BitArray doesn't have a constructor taking an existing array, offset and count... that would make it significantly more efficient. (As would a "slice copy" operation, of course.)

A more general purpose option would be to create an extension method precisely for that "slice copy" part:

public static BitArray CopySlice(this BitArray source, int offset, int length)
{
    // Urgh: no CopyTo which only copies part of the BitArray
    BitArray ret = new BitArray(length);
    for (int i = 0; i < length; i++)
    {
         ret[i] = source[offset + i];
    }
    return ret;
}

Then:

var smallBitArrays = Enumerable
    .Range(0, bigBitArray.Length / 32)
    .Select(offset => bigBitArray.CopySlice(offset * 32, 32))
    .ToList();

people

See more on this question at Stackoverflow