我有一个构造函数,它创建一个BitArray对象,它向用户询问他们想要使用多少'位'。然后它使用无符号字符来存储需要保存多个字节的字节。然后我希望创建允许用户“设置”某个位的方法,并且还要在最后显示全部字节集。但是,我的Set方法似乎并没有改变这个位,或者我的Print函数(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;
}
也许我很困惑..但它看起来像你正在使用'char []'数组来保存每个索引中的单个'位'值。如果是这样的话,你的'Set'函数应该只是:'barray [index - 1] ='1';'?如果阵列中的每个char都保持1或0,则不需要移位。 – 2013-04-05 01:27:14