简化了位集算法的尝试



试图简化涉及位数组操作的赋值的这段工作但冗长的代码。到目前为止,我对set函数的了解(将数组中索引处的位设置为1):

// set bit with given index to 1
void BitArray::Set   (unsigned int index){
switch( index%8 )
{
case 7: 
barray[index/8] = barray[index/8] | 1;
break;
case 6: 
barray[index/8] = barray[index/8] | 2;
break;
case 5:
barray[index/8] = barray[index/8] | 4;
break;
case 4:
barray[index/8] = barray[index/8] | 8;
break;
case 3:
barray[index/8] = barray[index/8] | 16;
break;
case 2:
barray[index/8] = barray[index/8] | 32;
break;
case 1:
barray[index/8] = barray[index/8] | 64;
break;
case 0:
barray[index/8] = barray[index/8] | 128;
break;
default: cout << "Error. Index less than 0. Cannot set the bit.";
} // end of switch( index )*/

因此,我要处理一个char数组中的一个元素,在这个元素上,我要遍历保持该索引的8位。

以下是我简化switch语句的尝试:

int location = index / 8;
int position = index % 8;
mask = (1 << position);
barray[location] = barray[location] | Mask(index);

这不是我想要的方式(如果我传入2作为要更改的索引,则将索引5处的位设置为"1")

感谢任何输入

实际上,读取位的顺序不是C(或C++)读取位的次序。您似乎是从左到右读取位,而对于C,"1"是"00000001"。因此,您应该以这种方式修复您的语句(也使用"|="运算符):

barray[location] |= 1 << (7 - position);

(我忽略了你的函数Mask(index),因为你没有向我们描述它)

看起来您需要的是定义int position = 7 - (index % 8);

最新更新