#include #include "BitSet.h" std::string BitSet::asHex() const { static const char digits[] = "0123456789ABCDEF"; int digitCount = (max() / 4) + 1; std::string result; result.reserve(digitCount); int digit = 0; for (int bit = digitCount * 4 - 1; bit >= 0; bit--) { digit <<= 1; if (get(bit)) { digit |= 1; } if ((bit % 4) == 0) { result += digits[digit]; digit = 0; } } return result; } BitSet::BitSet() { } BitSet::BitSet(std::string asHex) { loadFromHex(asHex); } void BitSet::loadFromHex(std::string asHex) { clear(); unsigned hexSize = asHex.size(); int bit = hexSize * 4 - 1; for (unsigned i = 0; i < hexSize; i++) { int digit; char ch = asHex[i]; if ((ch >= '0') && (ch <= '9')) { digit = ch - '0'; } else if ((ch >= 'A') && (ch <= 'F')) { digit = ch - 'A' + 10; } else if ((ch >= 'a') && (ch <= 'f')) { digit = ch - 'a' + 10; } else { clear(); return; } set(bit--, digit & 8); set(bit--, digit & 4); set(bit--, digit & 2); set(bit--, digit & 1); } assert(bit == -1); } std::string BitSet::asBinary() const { unsigned bit = max(); std::string result; result.reserve(bit); while (true) { result += get(bit)?'1':'0'; if (!bit) break; bit--; } return result; } bool BitSet::get(unsigned bit) const { return _bits.count(bit); } unsigned BitSet::max() const { std::set< unsigned >::reverse_iterator it = _bits.rbegin(); if (it == _bits.rend()) { return 0; } else { return *it; } } void BitSet::set(unsigned bit, bool value) { if (value) { _bits.insert(bit); } else { _bits.erase(bit); } } void BitSet::clear(unsigned bit) { set(bit, false); } void BitSet::clear() { _bits.clear(); } BitSet &BitSet::operator &=(BitSet const &other) { std::set< unsigned >::iterator it = _bits.begin(); while (it != _bits.end()) { std::set< unsigned >::iterator current = it; it++; if (!other.get(*current)) { _bits.erase(current); } } return *this; } #ifdef UNIT_TEST_BIT_SET #include int main(int argc, char *argv[]) { while (std::cin) { std::string s; std::cin>>s; BitSet bs(s); for (int i = bs.size(); i >= 0; i--) { std::cout<<(bs.get(i)?'1':'0'); } std::cout<<'\n'<