Clever Humans

Logo

Clever Humans do the darnedest things!

Categories

11 November 2007

BitArray Annoyance

by Patrick

The BitArrayclass in .Net is used to store a set of true and false values. It really is simply an array of Boolean values. And if Microsoft had left it there … just a specialized collection of bools, no one would have said anything. They could have called it BoolArray and everyone would have gone home happy. Instead, however, they chose to name the class BitArray and provide methods on that class to do logical operations on the array of Booleans. They added AND, OR, NOT, and XOR. So great! Now I can do bitwise operations on my array of Booleans.

But what I can’t do is transform that BitArray into an integer value. Arguably, there are good reasons for this. The BitArray class is designed to hold very large numbers of bits. It can hold more bits than can fit into any single data type. So they couldn’t simply provide a ToInt32() or ToInt64() method and be done with it. No single data type could hold all the values of a BitArray.

But there is an answer to this problem. In fact, Microsoft had already found that answer for the BitArray. If you look at the constructor of the BitArray you will see that it can take an array of integers. MSDN has this to say about the constructor:

The number in the first values array element represents bits 0 through 31, the second number in the array represents bits 32 through 63, and so on. The Least Significant Bit of each integer represents the lowest index value: “ values [0] & 1” represents bit 0, “ values [0] & 2” represents bit 1, “ values [0] & 4” represents bit 2, and so on.

So the solution should be obvious. A method is needed to return an array of integers. The BitArray class needs a ToInt32Array method that works in the same way as the constructor does. This way you can get back an array of integers just like you put into it.

Here is my version of such a function:

        int[] ToInt32Array(BitArray ba)
        {
            int[] values = new int[ba.Length/32];
            Byte[] bytes = new byte[ba.Length];
            ba.CopyTo(bytes, 0);
            for (int a = 0; a <= values.GetUpperBound(0); a++)
            {
                values[a] = BitConverter.ToInt32(bytes, a * 4);
            }
            return values;
        }

It takes a BitArray as a parameter and returns an array of integers.

tags: programming