Did I implement the increment operator for my dynamic bit set correctly because it is giving unexpected output

93 Views Asked by At

I have my a overloaded increment operator function for my DynamicBitset class.

DynamicBitset DynamicBitset::operator++(int)
{

int byteCount = 0;
unsigned int count = 0;
unsigned int lastCharBitIndex;

while ((this->array[byteCount] << count & 1) != 0)
{
    if ((int)(count / 8) >= this->arrayLength)
    {
        this->zeroOutArray();
        this->addByte(1);
        return *this;
    }
    if (count % 8 == 0)
    {
        byteCount = count / 8;
    }
    count++;
}

lastCharBitIndex = count - (byteCount * 8);

if (count % 8 != 0)
{
    zeroUpTo(count);
    this->array[byteCount] = this->array[byteCount] + (unsigned char)(pow(2, lastCharBitIndex - 1));
}
else
{
    zeroUpTo(count);
    this->array[byteCount] += 1;
}

std::cout << "This Ran!";

return *this;
}

Here are the private variable declarations.

unsigned char* array;
unsigned int arrayLength;
unsigned int bitLength;

But when I add a byte like 97 or 'a' on the ascii table and try to increment it, it gives me the value 221 when it should be 98.

1

There are 1 best solutions below

8
Christian Phillips On

Turns out the return type was one of the problems. And also my original algorithm just wasn't correct which makes sense because I was tired when I wrote it. So I just rewrote it today and it works.

void DynamicBitset::operator++(int)
{
unsigned int byteCount = 0;
unsigned int bitIndex = 0;

while ((this->array[byteCount] >> bitIndex & 1) != 0)
{
    if ((unsigned int)(bitIndex / 8) > this->arrayLength)
    {
        this->zeroOutArray();
        this->addByte(1);
        return;
    }
    if (bitIndex % 8 == 0)
    {
        byteCount = bitIndex / 8;
    }
    bitIndex++;
}

unsigned int subArrayLength = (unsigned int)(bitIndex / 8);
unsigned int lastCharBitIndex = bitIndex - (subArrayLength * 8);
unsigned char powerMask = 1;

this->zeroUpTo(bitIndex);

this->array[subArrayLength] += (powerMask << lastCharBitIndex);
}