1 2 3 4 5 6 7
|
if constexpr (sizeof(bitarr<1>) != 1)
{
throw std::runtime_error
{
"1 byte is necessary for (CHAR_BIT*2) bits."
};
}
|
This means a bitarr with 1 bit must be exactly 1 byte long. You can't store a pointer to an array because the pointer alone is 4 or 8 bytes, depending on whether you're compiling a 32 or 64 bit program . You can't store an array of ints because an int is typically 4 bytes.
You must use an array of chars and it must be stored directly in the bitarr<>. Actually, you should use unsigned char.
To get, set, and clear the i'th bit, you'll need to know the
index in the array of the byte that contains it, and its
position within that byte. For the position, you'll find it easier to create the bit mask for it. In other words, an unsigned char that has just 1 bit set - the one corresponding to the bit you're interested in.
For these, I suggest two private members:
1 2 3 4 5
|
// find the index of the byte in arr that contains bit #pos
size_t index(size_t pos);
// Return the bit mask for bit #pos
unsigned char mask(size_t pos);
|
Test these functions. For example, you could temporarily make them public and add this to main():
1 2 3 4 5
|
bitarr<10> ba;
for (unsigned i=0; i<10; ++i) {
std::cout << "pos " << std::dec << i << " is byte " << ba.index(i)
<< " and mask 0x" << std::hex << (int)ba.mask(i) << '\n';
}
|
pos 0 is byte 0 and mask 0x1
pos 1 is byte 0 and mask 0x2
pos 2 is byte 0 and mask 0x4
pos 3 is byte 0 and mask 0x8
pos 4 is byte 0 and mask 0x10
pos 5 is byte 0 and mask 0x20
pos 6 is byte 0 and mask 0x40
pos 7 is byte 0 and mask 0x80
pos 8 is byte 1 and mask 0x1
pos 9 is byte 1 and mask 0x2 |
Once you have these, the rest of the code is simple, but you may have to brush up on binary numbers and how to manipulate them in C++