我是否正确实现了动态位设置的增量运算符,因为它给出了意外的输出

问题描述 投票:0回答:1

我的 DynamicBitset 类有一个重载的增量运算符函数。

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;
}

这是私有变量声明。

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

但是当我在 ascii 表上添加像 97 或“a”这样的字节并尝试递增它时,它给我的值是 221,而它应该是 98。

c++ bitset
1个回答
0
投票

事实证明返回类型是问题之一。而且我原来的算法也不正确,这是有道理的,因为我写它时很累。所以我今天重写了它,它起作用了。

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.