C#中将BitArray类型转换为十进制整数的一个思路

    //
        // 摘要:
        //     将BitArray转换为一个十进制整数。
        // 参数:
        //     ba, 下表从低到高的顺序 与十进制整数的二进制形式从低到高的顺序一致
        static int BitArray2Int(BitArray ba)
        {
            Int32 ret = 0;
            for (Int32 i = 0; i < ba.Length; i++)
            {
                if (ba.Get(i))
                {
                    ret |= (1 << i);
                }
            }
            return ret;
        }

 

测试程序:

        static void BitArrayTest()
        {
            BitArray myBA = new BitArray(8);
            myBA.SetAll(true);
            Console.WriteLine("myBA Values:");
            int i = 0;
            foreach (Boolean bl in myBA)
            {
                Console.WriteLine("    [{0}]:    {1}", i++, bl);
                if ((i % 4) == 0)
                {
                    Console.WriteLine();
                }
            }
            int decInt = BitArray2Int(myBA);
            Console.WriteLine("\nAfter Converting...");
            Console.WriteLine("myBA's Decimal Number:\n\t" + decInt);
        }

你可能感兴趣的:(array)