从动态数组中设置位然后显示它

时间:2013-04-05 00:24:47

标签: c++ set overloading bit-manipulation bit

我有一个构造函数,它创建一个BitArray对象,询问用户他们想要使用多少“位”。然后它使用无符号字符来存储保存许多字符所需的字节数。然后,我希望创建允许用户“设置”某个位的方法,并且还要在结尾处显示完整的字节集。但是,我的Set方法似乎没有改变位,或者我的Print函数(The Overload)似乎实际上并没有打印实际的位。有人可以指出问题吗?

构造

BitArray::BitArray(unsigned int n)
{

//Now let's find the minimum 'bits' needed

n++;
//If it does not "perfectly" fit
//------------------------------------ehhhh
if( (n % BYTE) != 0)
    arraySize =(n / BYTE);
else
    arraySize = (n / BYTE) + 1;

//Now dynamically create the array with full byte size
barray = new unsigned char[arraySize];

//Now intialize bytes to 0
for(int i = 0; i < arraySize; i++)
{
    barray[i] = (int) 0;
}

}

设置方法:

    void BitArray::Set(unsigned int index)
{
        //Set the Indexed Bit to ON
        barray[index/BYTE] |= 0x01 << (index%BYTE);
}

打印重载:

 ostream &operator<<(ostream& os, const BitArray& a)
{  
        for(int i = 0; i < (a.Length()*BYTE+1); i++)
        {
            int curNum = i/BYTE;
            char charToPrint = a.barray[curNum];
            os << (charToPrint & 0X01);
            charToPrint >>= 1;
        }
    return os;
}

1 个答案:

答案 0 :(得分:0)

    for(int i = 0; i < (a.Length()*BYTE+1); i++)
    {
        int curNum = i/BYTE;
        char charToPrint = a.barray[curNum];
        os << (charToPrint & 0X01);
        charToPrint >>= 1;
    }

每次运行循环时,都会为charToPrint获取新值。这意味着操作charToPrint >>= 1;是无用的,因为该修改不会在下一次循环运行时执行。因此,您始终只打印阵列的每个char的第一位。