using System.Diagnostics;
namespace Test
{
class Program
{staticvoidMain(string[] args){
BitSet bitset = new BitSet(8);
bitset.Set(4, true);
Debug.WriteLine(bitset.ToString());
Debug.WriteLine(bitset.ToInt());}}}
输出
00010000
16
BitSet实现类
using System;
using System.Text;
namespace Test
{
class BitSet
{
public int count;
private bool[] bitset;
public BitSet(int count){
this.count = count;
bitset = new bool[count];}
public bool this[int index]{
get
{CheckIndexLegal(index);return bitset[index];}
set
{CheckIndexLegal(index);
bitset[index]= value;}}
public intSize(){return count;}
public BitSet Clone(){
BitSet bit = new BitSet(count);for(int index =0; index < count; index++){
bit[index]= this[index];}return bit;}
public voidSet(int index, bool value = true){CheckIndexLegal(index);
this[index]= value;}
public voidSet(int startIndex,int endIndex, bool value = true){CheckIndexLegal(startIndex);CheckIndexLegal(endIndex);for(int index = startIndex; index < endIndex; index++){
this[index]= value;}}
public voidClear(){for(int index =0; index < count; index++){
this[index]= false;}}
public voidClear(int index){CheckIndexLegal(index);
this[index]= false;}
public voidClear(int startIndex,int endIndex){CheckIndexLegal(startIndex);CheckIndexLegal(endIndex);for(int index = startIndex; index < endIndex; index++){
this[index]= false;}}
public bool Equals(BitSet bit){if(this.count == bit.count){for(int index =0; index < this.count; index++){if(this[index]!= bit[index]){return false;}}return true;}return false;}
public bool Get(int index){CheckIndexLegal(index);return this[index];}
public BitSet Get(int startIndex,int endIndex){CheckIndexLegal(startIndex);CheckIndexLegal(endIndex);
var length = endIndex - startIndex;
BitSet bit = new BitSet(length);for(int index =0; index < length; index++){
bit[index]= this[index + startIndex];}return bit;}
public bool IsEmpty(){for(int index =0; index < count; index++){if(this[index]){return false;}}return true;}
private voidCheckIndexLegal(int index){if(index <0|| index >= count){
throw new IndexOutOfRangeException();}}
public override string ToString(){
StringBuilder builder = new StringBuilder();for(int index = count -1; index >=0; index--){
builder.Append((this[index]?1:0));}return builder.ToString();}
public intToInt(){return Convert.ToInt16(this.ToString(),2);}}}