1 classBitArray2 {3 Public:4 enum5 {6Bits_per_long =sizeof(unsignedLong)*8,7 };8 9BitArray (): Array_ (0) { }TenBitArray (unsignedLongNR): Array_ (0) One { A Reset (NR); - } - the~bitarray () {if(Array_) Delete [] array_;} - -BitArray (Constbitarray&RHS) - { + if(Rhs.array_) - { +Array_ =NewUnsignedLong[Rhs.nr_long_]; Amemcpy (Array_, Rhs.array_, Rhs.nr_long_ *sizeof(unsignedLong)); atNr_long_ =Rhs.nr_long_; -Nr_bits_ =Rhs.nr_bits_; - } - } - -bitarray&operator=(Constbitarray&RHS) in { - if( This= = &RHS) to { + return* This; - } the * if(Array_) $ {Panax Notoginseng Delete [] array_; - } the + if(Rhs.array_) A { theArray_ =NewUnsignedLong[Rhs.nr_long_]; +memcpy (Array_, Rhs.array_, Rhs.nr_long_ *sizeof(unsignedLong)); -Nr_long_ =Rhs.nr_long_; $Nr_bits_ =Rhs.nr_bits_; $ } - return* This; - } the - BOOL operator[] (std::size_t nr)Wuyi { the if(Nr >=nr_bits_) - return false; Wu -UnsignedLongret = Array_[bitword (NR)] &bitmask (NR); About if(ret) $ return true; - Else - return false; - } A + BOOLTestbit (std::size_t nr) the { - return This-operator[] (NR); $ } the the voidSetbit (unsignedLongnr) the { the if(Nr >=nr_bits_) - { in return; the } the AboutArray_[bitword (NR)] |=bitmask (NR); the } the the voidClearbit (unsignedLongnr) + { - if(Nr >=nr_bits_) the {Bayi return; the } the -Array_[bitword (NR)] &= ~bitmask (NR); - } the the voidReset (unsignedLongnr_bits) the { the if(Array_) - { the Delete [] array_; the } the 94UnsignedLongReal_nr_bits =align (nr_bits); theNr_long_ =Getnrlong (real_nr_bits); theArray_ =NewUnsignedLong[Nr_long_]; theNr_bits_ =nr_bits;98memset (Array_,0, nr_long_*sizeof(unsignedLong)); About } - 101 Private:102 103UnsignedLongGetnrlong (unsignedLongNR) {returnnr/Bits_per_long;}104UnsignedLongAlign (unsignedLongnr) the {106 return(Nr + (bits_per_long-1)) & (~ (bits_per_long-1));107 }108 109UnsignedLongBitword (unsignedLongnr) the {111 returnnr/Bits_per_long; the }113 theUnsignedLongBitmask (unsignedLongnr) the { the returnnr%Bits_per_long;117 }118 119UnsignedLongNr_bits_; -UnsignedLongNr_long_;121UnsignedLong*Array_;122};
Use the following,
#include <iostream>#include<string>#include<string.h>#include"BitArray.h"intMainvoid) {BitArray A (Ten); A.setbit (1); cout<< a[1] <<Endl; A.clearbit (1); cout<< a[1] <<Endl; A.setbit (Ten); cout<< a[Ten] <<Endl; return 0;}
Array of Bits