Created
March 14, 2014 07:27
-
-
Save jiaguofang/9543452 to your computer and use it in GitHub Desktop.
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
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