【发布时间】:2015-04-15 20:51:20
【问题描述】:
试图为涉及位数组操作的赋值简化这个工作但冗长的代码。到目前为止我所拥有的 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”)
感谢您的任何意见
【问题讨论】:
-
既然你已经颠倒了位序,那么只需颠倒位置的顺序(例如
7 - position) -
就是这样!谢谢,我现在记得在课堂上听说过,我希望我能早点记得!
标签: c++ arrays bit-manipulation bit bitmask