Skip to content

Instantly share code, notes, and snippets.

@jiaguofang
Created March 14, 2014 07:27
Show Gist options
  • Save jiaguofang/9543452 to your computer and use it in GitHub Desktop.
Save jiaguofang/9543452 to your computer and use it in GitHub Desktop.
class BitArray {
public:
BitArray(unsigned capacity) {
bit_capacity = capacity;
byte_capacity = capacity / 8 + 1;
data = new char[capacity];
memset(data, 0, byte_capacity);
}
~BitArray() {
delete[] data;
}
void set(size_t pos, bool val = true) {
if (val)
data[getBytePos(pos)] |= 1 << getBitPosInByte(pos);
else
data[getBytePos(pos)] &= ~(1 << getBitPosInByte(pos));
}
bool test(size_t pos) {
return (data[getBytePos(pos)] & 1 << getBitPosInByte(pos)) != 0;
}
private:
int getBytePos(size_t pos) {
return pos / 8; // pos >> 3
}
int getBitPosInByte(size_t pos) {
return pos % 8;
}
private:
char *data;
int bit_capacity;
int byte_capacity;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment