C# BitArray 例項

diaomu7437發表於2012-04-13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Hash
{
    class Program
    {
       
        static void Main(string[] args)
        {
            byte a = 5;
            BitArray myBit1 = new BitArray(a);//5個字位,初始化為false
            //myBit1為5位,取用預設初始化,5位都為 False。即為0,由此可見,平時一位的值0和1在C#裡面變成False和True;
            myBit1[0] = true;
            myBit1[1] = true;
            
            Console.Write("my Bit1     Count:{0},length:{1},值如下:\n", myBit1.Count, myBit1.Length);
            PrintValues(myBit1, 8);//每8個元素為一行列印元素

            byte [] myByte1 = new byte[] { 1, 2, 3, 4, 5 };//位元組陣列,byte為0-255的型別
            BitArray myBit2 = new BitArray(myByte1);
            //使用myByte1初始化myBit2;共有5*8個位元組位;
            //myByte2為byte陣列,內容為1,2,3,4,5;二進位制就是00000001,00000010,00000011,00000100,00000101,myBA3就為相應的5*8=40位
            //在myByte2中數字按照二進位制數從右到左存取
            Console.Write("my  Bit2     Count:{0},length:{1},值如下:\n", myBit2.Count, myBit2.Length);
            PrintValues(myBit2, 8);//每8個元素為一行列印元素

            bool[] myBools = new bool[5] { true, false, true, true, false };
            BitArray myBA4 = new BitArray(myBools);
            //看輸出,bool就想當於一位,myBools是長度為5的陣列,變成myBA4後,也是5位;
            Console.Write("myBA4     Count:{0},length:{1},值如下:\n", myBA4.Count, myBA4.Length);
            PrintValues(myBA4, 8);//每8個元素為一行列印元素

            int[]  myInts  = new int[5] { 6, 7, 8, 9, 10 };
            BitArray myBA5 = new BitArray( myInts );
            //int是32位的,5個,換成BitArray當然就是5*32=160。
            Console.Write("myBA5    Count:{0},length:{1},值如下:\n", myBA5.Count, myBA5.Length);
            PrintValues(myBA5, 8);//每8個元素為一行列印元素





            Console.ReadKey();

        }
        public static void PrintValues(IEnumerable myList, int myWidth) //myWidth指定每行顯示的個數
        {
            int i = myWidth;
            foreach (Object obj in myList)  //迭代一列數
            {
                if (i <= 0)
                {
                    i = myWidth;
                    Console.WriteLine();
                }
                i--;
                Console.Write("{0,7}", obj);//顯示第0個資料obj,佔7個符號的位置
                
            }
            Console.WriteLine();
        }
    }
}

轉載於:https://www.cnblogs.com/wang7/archive/2012/04/13/2446353.html

相關文章