0

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

Tyler Kelly
  • 564
  • 5
  • 23

2 Answers2

4

Actually the order you read bits is not the order C (or C++) reads bits. You appear to be reading bits from left to right, while for C "1" is "00000001". So you should fix your statement this way (also using the "|=" operator) :

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

(I'm ignoring your function Mask(index) as you did not describe it to us)

Ekleog
  • 1,054
  • 7
  • 19
  • thanks! yeah i forgot to take that Mask function out and replace with the one i declare in the method, but same thing essentially – Tyler Kelly Apr 15 '15 at 21:02
2

It looks like what you need is to define int position = 7 - (index % 8);.

Amnon Shochot
  • 8,998
  • 4
  • 24
  • 30