// bitarray.cc see license.txt for copyright and terms of use // code for bitarray.h #include "bitarray.h" // this module #include "flatten.h" // Flatten #include // memset BitArray::BitArray(int n) : numBits(n) { allocBits(); clearAll(); } void BitArray::allocBits() { bits = new unsigned char[allocdBytes()]; } BitArray::~BitArray() { delete[] bits; } BitArray::BitArray(Flatten&) : bits(NULL) {} void BitArray::xfer(Flatten &flat) { flat.xferInt(numBits); if (flat.reading()) { allocBits(); } flat.xferSimple(bits, allocdBytes()); } BitArray::BitArray(BitArray const &obj) : numBits(obj.numBits) { allocBits(); memcpy(bits, obj.bits, allocdBytes()); } void BitArray::operator=(BitArray const &obj) { if (numBits != obj.numBits) { delete[] bits; numBits = obj.numBits; allocBits(); } memcpy(bits, obj.bits, allocdBytes()); } bool BitArray::operator== (BitArray const &obj) const { if (numBits != obj.numBits) { return false; } // this relies on the invariant that the unused trailing // bits are always set to 0 return 0==memcmp(bits, obj.bits, allocdBytes()); } void BitArray::clearAll() { memset(bits, 0, allocdBytes()); } void BitArray::invert() { int allocd = allocdBytes(); for (int i=0; i> 1) & 0x55) { // 01010101 return true; } } return false; // no such pair } BitArray stringToBitArray(char const *src) { int len = strlen(src); BitArray ret(len); for (int i=0; i> 3] == 0) { // yes, skip to next curBit += 8; if (curBit >= arr.numBits) { return; // done iterating } } } // this could be made a little faster by using the trick to scan // for the first nonzero bit.. but since I am only going to scan // within a single byte, it shouldn't make that much difference if (arr.test(curBit)) { return; // found element } curBit++; } } // -------------------- test code ------------------- #ifdef TEST_BITARRAY #include "test.h" // USUAL_MAIN string toStringViaIter(BitArray const &b) { stringBuilder sb; int index = 0; for (BitArray::Iter iter(b); !iter.isDone(); iter.adv()) { while (index < iter.data()) { sb << "0"; index++; } sb << "1"; index++; } while (index < b.length()) { sb << "0"; index++; } return sb; } void testIter(char const *str) { BitArray b = stringToBitArray(str); b.selfCheck(); string s1 = toString(b); string s2 = toStringViaIter(b); if (s1 != s2 || !s1.equals(str)) { cout << "str: " << str << endl; cout << " s1: " << s1 << endl; cout << " s2: " << s2 << endl; xbase("testIter failed"); } // also test the inverter BitArray c = ~b; c.selfCheck(); stringBuilder inv; int len = strlen(str); for (int i=0; i