C#位数组BitArray

时间:2024-10-09 22:47:52
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Collections; using System.Diagnostics; using System.Collections.Specialized; namespace TESTT { class Program { static void DisplayBit(string tag,BitArray bits) //将位数组输出 { if(tag!="") Console.Write(tag+":"); foreach (bool b in bits) { Console.Write(b?1:0); } Console.WriteLine(); } static void Main(string[] args) { var bits = new BitArray(8); //创建一个8位的位数组 //设置全部位 bits.SetAll(true); DisplayBit("设置全部为true后",bits); //设置指定位 bits.Set(1,false); DisplayBit("设置下标1为false后",bits); //按索引器设置 bits[5] = false; DisplayBit("设置下标5为false后", bits); //Not取反运算 bits.Not(); DisplayBit("bits取反后", bits); //更改位数组的长度 bits.Length = 16; bits[9] = true; DisplayBit("设置下标9为false后", bits); //新建 var bits2 = new BitArray(bits); bits2[0] = true; bits2[2] = true; bits2[4] = true; bits2[6] = true; bits2[8] = true; bits2[10] = true; bits2[12] = true; //Or或运算 DisplayBit("", bits); Console.Write(" or"); DisplayBit("", bits2); Console.Write("="); bits.Or(bits2); DisplayBit("", bits); //And运算 DisplayBit("", bits); Console.Write(" and"); DisplayBit("", bits2); Console.Write("="); bits.And(bits2); DisplayBit("", bits); //Xor运算 DisplayBit("", bits); Console.Write(" xor"); DisplayBit("", bits2); Console.Write("="); bits.Xor(bits2); DisplayBit("", bits); Console.ReadKey(); } } }