100 likes | 273 Views
Lecture 7 – bitset. 1. Main Index. Contents. Bitset model : 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 member[0] member[1] 操作: vectorIndex: 位 i 对应的 vector 下标;. 1 1 1 1 1 1 1 1. 1 1 1 1 1 1 1 1. 2. Main Index. Contents. Implementing the bitVector Class.
E N D
Lecture 7 – bitset 1 Main Index Contents • Bitset model: • 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 • member[0] member[1] • 操作:vectorIndex: 位i 对应的vector下标; 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
2 Main Index Contents Implementing the bitVector Class • bitMask() returns an unsigned character value containing a 1 in the bit position representing i.
Bitvector class bitVector { public: bitVector(int numBits = 16); bitVector(int b[], int n); bitVector& operator= (int v); bitVector& operator= (char c); int size() const; int bit(int i) const; void set(int i); void clear(int i); void clear(); bitVector operator~ (); void write(fstream& ostr); void read(fstream& istr, int numBits); friend ostream& operator<< (ostream& ostr, const bitVector& x);
Bitvector private: int numberOfBits; int vectorSize; vector<unsigned char> member; int vectorIndex(int i) const; unsigned char bitMask(int i) const; };
Bitvector int bitVector::vectorIndex(int i) const { return i >> 3; //i 右移3位,相当与除8 } unsigned char bitVector::bitMask(int i) const { return 1 << (7 - (i & 7)); //掩码,可置位和清零 } //1左移0-7位 //余数为0则最左边的位置1,余7则最右边的位置1 bitVector::bitVector(int numBits): numberOfBits(numBits) { vectorSize = (numberOfBits+7) >> 3; member.resize(vectorSize); }
Bitvector bitVector operator| (const bitVector& x, const bitVector& y) { int i; if (x.numberOfBits != y.numberOfBits) throw rangeError("bitVector |: bit vectors are not the same size"); bitVector tmp(x.numberOfBits); for (i = 0; i < x.vectorSize; i++) tmp.member[i] = x.member[i] | y.member[i]; return tmp; }
Bitvector bitVector bitVector::operator~ () { bitVector tmp(numberOfBits); for (int i = 0; i < vectorSize; i++) tmp.member[i] = ~member[i]; return tmp; }
Bitvector int bitVector::bit(int i) const //返回第i位的值 { if (i < 0 || i >= numberOfBits) throw indexRangeError( "bitVector bit(): bit out of range", i, numberOfBits); if ((member[vectorIndex(i)] & bitMask(i)) != 0) return 1; else return 0; }
Bitvector void bitVector::set(int i) { if (i < 0 || i >= numberOfBits) throw indexRangeError( "bitVector set(): bit out of range", i, numberOfBits); member[vectorIndex(i)] |= bitMask(i); }
Bitvector void bitVector::clear(int i) { if (i < 0 || i >= numberOfBits) throw indexRangeError( "bitVector clear(): bit out of range", i, numberOfBits); member[vectorIndex(i)] &= ~bitMask(i); }