0

I'm working on a bit vector class that I'm using in a current project.

Basicly BitVector is a container class for storing and manipulating data a bit level.

I have two member fuctions for "setting" and "getting" bits at a given index.

```
// Returns the bit at the specified index.
unsigned char BitVector::at(int index)
{
if (index < 0 || index >= size)
throw; // ("Index outside the range of vector: " + index);
int byteValue = vector[index >> 3] & 0xff;
return (unsigned char)((byteValue >> (7 - (index & 0x7))) & 1);
}
// Replaces the bit at index with that specified by value.
void BitVector::replace(int index, unsigned char value)
{
if (index < 0 || index >= size)
throw ;// ("Index outside the range of vector: " + index);
if (!(value == 0 || value == 1))
throw; // ("Invalid value for bit vector: " + value);
int byteValue = vector[index >> 3] & 0xff;
if (value == 1)
byteValue = (unsigned char)(byteValue | (1 << (7 - (index & 0x7)))); // Left shift 1, then bitwise OR.
else
byteValue = (unsigned char)(byteValue & ~(1 << (7 - (index & 0x7)))); // Left shift 1, take complement, then bitwise AND.
vector[index >> 3] = (unsigned char)(byteValue & 0xff);
}
```

I would like to implement the subscript operater "[]" as a simpler/clearer way of accessing the bit data rather than using the above functions.

So far I have this:

```
unsigned char& BitVector::operator[](int index) const
{
assert(index >= 0 || index < size);
int byteValue = vector[index >> 3] & 0xff;
unsigned char rtn_value = (unsigned char)((byteValue >> (7 - (index & 0x7))) & 1);
//unsigned char rtn_value = at(index);
return (unsigned char&)rtn_value;
}
```

As this member function requires code to extract the required bit from the byte, it can not be used to both 'get' and 'set'.

Is there any way can achieve this with the subscript operator?

Thanks in advance...

Milton