1: // bit_array -- Implement a subscriptable array of bits, get and set individual bits. 3: #include "bit_array.H" 6: bit_array::bit_array(long n) : rows(1), cols(n){ // construct a 1-D bit_array 7: int sz = rows*cols/8 + (rows*cols % 8 == 0 ? 0 : 1); // size in bytes 8: bytes = new unsigned char[sz]; // allocate the array storage 9: } 11: bit_array::bit_array(long m, long n) : rows(m), cols(n) { // construct a 2-D bit_array 12: int sz = rows*cols/8 + (rows*cols % 8 == 0 ? 0 : 1); // size in bytes 13: bytes = new unsigned char[sz]; // allocate the array storage 14: } 16: bit_array::~bit_array() { // destroy a bit_array 17: delete[] bytes; // reclaim the array storage 18: } 20: int bit_array::operator()(long i) { // fetch a bit from a 1-D bit_array 21: return operator()((long)0, i); // transform into 2-D fetch 22: } 24: int bit_array::operator()(long i, long j) { // fetch a bit from a 2-D bit_array 25: int k = i*cols + j; // bit number as 1-D subscript 26: int sub = k / 8; // byte number as 1-D subscript 27: int bitno = k % 8; // bit number within that byte 28: int mask = 1 << bitno; // mask for that bit 29: int bit = bytes[sub] & mask; // fetch the bit 30: bit = bit ? TRUE : FALSE; // square up to TRUE/FALSE value 31: return bit; // return that value 32: } 34: void bit_array::set(long i, int val) { // set a bit in a 1-D bit_array 35: set((long)0, i, val); // transform to 2-D set 36: } 38: void bit_array::set(long i, long j, int val) { // set a bit in a 2-D bit_array 39: int k = i*cols + j; // bit number as 1-D subscrpt 40: int sub = k / 8; // byte number as 1-D subscript 41: int bitno = k % 8; // bit number within that byte 42: int mask = 1 << bitno; // mask for that bit 43: if (val) { // are we setting or clearing the bit? 44: bytes[sub] |= mask; // setting, or with mask 45: } else { // clearing, 46: bytes[sub] &= ~mask; // and with inverse of mask 47: } 48: }