Created
October 12, 2012 03:46
-
-
Save hindol/3877186 to your computer and use it in GitHub Desktop.
A BitSet class for C++03 and older
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <bool defaultState = false> | |
class BitSet | |
{ | |
public: | |
BitSet(std::size_t size) | |
: size_(size), bits_((size_ + 7) / 8, defaultState ? 0xff : 0x0) | |
{ | |
// Masks for each bit. Example, | |
// | |
// 7 6 5 4 3 2 1 0 | |
// 0x 0 0 0 1 0 0 0 0 <- masks_[4] | |
uint8_t mask = masks_[0] = 0x1; | |
for (int i = 1; i < 8; ++i) | |
{ | |
masks_[i] = (mask <<= 1); | |
} | |
} | |
bool Empty() const | |
{ return size_ == 0; } | |
std::size_t Size() const | |
{ return size_; } | |
void Set(std::size_t index, bool value = true) | |
{ | |
if (value) | |
bits_[index / 8] |= masks_[index % 8]; | |
else | |
Reset(index); | |
} | |
void Reset(std::size_t index) | |
{ | |
bits_[index / 8] &= ~masks_[index % 8]; | |
} | |
bool operator [](std::size_t index) | |
{ | |
return (bits_[index / 8] & masks_[index % 8]) != 0x0; | |
} | |
private: | |
const std::size_t size_; | |
std::vector<uint8_t> bits_; | |
uint8_t masks_[8]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment