Most efficient way to reverse the order of a BitArray?

Christopher picture Christopher · Jan 25, 2011 · Viewed 13k times · Source

I've been wondering what the most efficient way to reverse the order of a BitArray in C#. To be clear, I don't want to inverse the Bitarray by calling .Not(), I want to reverse the order of the bits in the array.

Cheers, Chris

Answer

Tim Lloyd picture Tim Lloyd · Jan 25, 2011
public void Reverse(BitArray array)
{
    int length = array.Length;
    int mid = (length / 2);

    for (int i = 0; i < mid; i++)
    {
        bool bit = array[i];
        array[i] = array[length - i - 1];
        array[length - i - 1] = bit;
    }    
}