I have made a bit array implementation that can be seen below:
unsigned int uint_size();
class Bitarray1D {
private:
unsigned int * array_;
int elements_;
int bits_;
public:
Bitarray1D(int bits);
~Bitarray1D();
void size(int& bits) const;
unsigned int count() const;
void setAll(int value);
void set(int index, int value);
int test(int index) const;
unsigned int operator [](int index) const;
void flip(int index);
std::string to_string() const;
private:
void init();
};
and some of the functions:
void Bitarray1D::init(){
if (bits_ == 0) throw std::invalid_argument("Can't initialize zero size array");
int number_of_elements = bits_;
std::cout << "unsigned int size: " << uint_size() << " bytes" << std::endl;
elements_ = std::ceil((bits_*1.0)/(uint_size()*1.0));
array_ = new unsigned int[elements_];
}
int Bitarray1D::test(int index) const {
if (index < 0 || index >= bits_) throw std::out_of_range("Index out of range");
int element = index / uint_size();
int bit = index % uint_size();
unsigned int temp_element = array_[element];
temp_element = temp_element >> bit;
unsigned int mul = 1;
temp_element = temp_element & mul;
return temp_element;
}
unsigned int Bitarray1D::operator [] (int index) const {
if (index < 0 || index >= bits_) throw std::out_of_range("Index out of range");
return test(index);
}
uint_size()
is a function that returns the size of an unsigned int
in bytes.
While this works well, i want to implement the assignment in array-like style as well, i.e.: bitarray[i] = 1;
In the current implementation this is not possible. In order to do so, I figured that []
operator in Bitarray
should return a "Bit object" with the appropriate operators like below:
class Bit{
private:
unsigned int& element_;
unsigned int index_;
int getValue() const{
// get value of bit
}
public:
Bit(unsigned int& element, unsigned int index): element_(element), index_(index){}
Bit& operator [] (int value){
return *this;
}
Bit& operator = (int value){
//assign value to the bit
}
friend std::ostream& operator<<(std::ostream& os, const Bit& bit){
os << bit.getValue();
return os;
}
};
This implementation works, but has two major problems:
Memory leak. In order for the
[]
operator inBitarray
to return a reference to aBit
object I have to return the following:Bit& Bitarray1D::operator [] (int index) const { return *(new Bit(..., ... )); }
I could change the
array_
of the bitarray to hold an array of classBit
, but then the whole point of theBitarray
is lost, which is smaller memory footprint.