Trying to simplify this working but lengthy code for an assignment involving bit array manipulation. What I have so far for the set function(sets the bit at index in the array to 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 )*/
So I'm going to a element in a char array, and at that elemnt I am then going through the 8 bits that holds and changing that index.
Here is my attempt at simplifying the switch statement:
int location = index / 8;
int position = index % 8;
mask = (1 << position);
barray[location] = barray[location] | Mask(index);
which doesnt work the way I intend(sets the bit at index 5 to '1' if I pass in 2 as the index to change)
Thanks for any input