C# BitArray 實例


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();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM