Skip to content

Instantly share code, notes, and snippets.

@AaronNGray
Created January 6, 2023 20:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AaronNGray/498b276ddfb05369e404f937aa091fc0 to your computer and use it in GitHub Desktop.
Save AaronNGray/498b276ddfb05369e404f937aa091fc0 to your computer and use it in GitHub Desktop.
lookahead bitset guard - ANDNZ
#include <cstddef>
#include <initializer_list>
template<size_t BITS>
class bitset
{
public:
bitset() : sizeInBits(BITS), sizeOfWord(sizeof(WORD) * 8), sizeInWords((BITS + (sizeof(WORD) * 8) - 1) / (sizeof(WORD) * 8)) {
for (size_t i = 0; i < sizeInWords; ++i)
data[i] = 0;
}
bitset(bitset<BITS>& bs) : bitset(bs.sizeInBits, bs.complement) {
for (size_t i = 0; i < sizeInWords; ++i)
data[i] = bs.data[i];
}
bitset(const bitset<BITS>& bs) : bitset(bs.sizeInBits, bs.complement) {
for (size_t i = 0; i < sizeInWords; ++i)
data[i] = bs.data[i];
}
bitset(const std::initializer_list<size_t> il) : bitset<BITS>() {
for (auto i = il.begin(); i != il.end(); ++i)
set(*i);
}
~bitset() {}
bitset& set(size_t element, bool v = true) {
size_t word = element / sizeOfWord;
size_t bit = element % sizeOfWord;
WORD value = ((WORD)1) << bit;
data[word] = (data[word] & ~value) | (v ? value : 0);
return *this;
}
template<size_t B>
friend inline bool AND(const bitset<B>& input, const bitset<B>& lookaheads) {
bool result = false;
for (size_t i = 0; i < lookaheads.sizeInWords; ++i)
result |= (input.data[i] & lookaheads.data[i]) != 0;
return result;
}
private:
typedef unsigned long long WORD;
const size_t sizeInBits;
const size_t sizeOfWord;
const size_t sizeInWords;
bool complement;
WORD data[(BITS + (sizeof(WORD) * 8) - 1) / (sizeof(WORD) * 8)];
};
int main(int argc, char *argv[]) {
bitset<63> input;
input.set(argc);
bitset<63> lookahead = {1, 3, 5};
bool result = AND(input, lookahead) ? 0 : 1;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment