Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to reverse the order of a BitArray?

Tags:

c#

bitarray

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

like image 722
Christopher Avatar asked Jan 25 '11 08:01

Christopher


People also ask

What is BitArray in C#?

The BitArray class manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0). It is used when you need to store the bits but do not know the number of bits in advance.


3 Answers

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;
    }    
}
like image 174
Tim Lloyd Avatar answered Sep 30 '22 12:09

Tim Lloyd


For a long array and relative few uses, just wrap it:

    class BitArrayReverse
    {
        private BitArray _ba;

        public BitArrayReverse(BitArray ba) { _ba = ba; }

        public bool this[int index]
        {
            get { return _ba[_ba.Length - 1 - index]; }
            set { _ba[_ba.Length - 1 - index] = value; }
        }

    }
like image 22
Henk Holterman Avatar answered Sep 30 '22 11:09

Henk Holterman


This will be the best way to reverse MSB <-> LSB of any length using XOR in the for loop

public static BitArray BitsReverse(BitArray bits)
{
    int len = bits.Count;
    BitArray a = new BitArray(bits);
    BitArray b = new BitArray(bits);

    for (int i = 0, j = len-1; i < len; ++i, --j)
    {
         a[i] = a[i] ^ b[j];
         b[j] = a[i] ^ b[j];
         a[i] = a[i] ^ b[j];
    }

    return a; 
} 
// in   010000011010000011100b
// out  001110000010110000010b
like image 23
fmDream Avatar answered Sep 30 '22 10:09

fmDream