C#学习日记 BitArray BitVector32

BitArray类可以重新设置大小,事先不知道大小的可以用它,它可以包含很多位。它是引用类型的。位里存储的是bool类型,有Not Or And Xor 方法。

using System;
using System.Collections;

namespace Sample
{
	public class MainEntryPoint
	{
		static int Main(string[] args)
		{
			var bits1 = new BitArray(8);
			bits1.SetAll(true);
			bits1.Set(1, false);
			bits1[5] = false;
			bits1[7] = false;
			Console.Write("initialized: ");
			DisplayBits(bits1);
			Console.WriteLine();
			Console.Write("not ");
			DisplayBits(bits1);
			bits1.Not();
			Console.Write(" = ");
			DisplayBits(bits1);
			Console.WriteLine();
			var bits2 = new BitArray(bits1);
			bits2[0] = true;
			bits2[1] = false;
			bits2[4] = true;
			DisplayBits(bits1);
			Console.Write(" or ");
			DisplayBits(bits2);
			Console.Write(" = ");
			bits1.Or(bits2);
			DisplayBits(bits1);
			Console.WriteLine();
			DisplayBits(bits2);
			Console.Write(" and ");
			DisplayBits(bits1);
			Console.Write(" = ");
			bits2.And(bits1);
			DisplayBits(bits2);
			Console.WriteLine();
			DisplayBits(bits1);
			Console.Write(" xor ");
			DisplayBits(bits2);
			Console.Write(" = ");
			bits1.Xor(bits2);
			DisplayBits(bits1);

			return 0;
		}
		static void DisplayBits(BitArray bits)
		{
			foreach(bool bit in bits)
			{
				Console.Write(bit ? 1: 0);
			}
		}
	}
	
}

BitVector结构是基于栈的,速度非常快,只能存储32位,存在一个整数里。section能选择片段的位置长度。

using System;
using System.Collections.Specialized;
using System.Text;

namespace Sample
{
	public class MainEntryPoint
	{
		static int Main(string[] args)
		{
			int received = 0x79abcdef;
			BitVector32 bits = new BitVector32(received);
			BitVector32.Section sectionA = BitVector32.CreateSection(0xfff);
			BitVector32.Section sectionB = BitVector32.CreateSection(0xff, sectionA);
			BitVector32.Section sectionC = BitVector32.CreateSection(0x7, sectionB);
			BitVector32.Section sectionD = BitVector32.CreateSection(0x7, sectionC);
			BitVector32.Section sectionE = BitVector32.CreateSection(0x3, sectionD);
			
			Console.WriteLine("SectionA: {0}",IntToBinaryString(bits[sectionA], true));
			Console.WriteLine("SectionB: {0}",IntToBinaryString(bits[sectionB], true));
			Console.WriteLine("SectionC: {0}",IntToBinaryString(bits[sectionC], true));
			Console.WriteLine("SectionD: {0}",IntToBinaryString(bits[sectionD], true));
			Console.WriteLine("SectionE: {0}",IntToBinaryString(bits[sectionE], true));

			return 0;
		}
		static string IntToBinaryString(int bits, bool removeTrailingZero)
		{
			var sb =new StringBuilder(32);

			for(int i = 0 ; i < 32; i++)
			{
				if((bits & 0x80000000) != 0)
				{
					sb.Append("1");
				}
				else
				{
					sb.Append("0");
				}
				bits = bits << 1;
			}
			string s = sb.ToString();
			if(removeTrailingZero)
			{
				return s.TrimStart('0');
			}
			else
			{
				return s;
			}
		}
	}
}


你可能感兴趣的:(C#学习日记)