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

2
  • 3
    Since you have reversed the bit order, just reverse the order of the position (eg 7 - position) Commented Apr 15, 2015 at 20:55
  • that was it! thanks, I now remember hearing about that in class and I wish I remembered sooner! Commented Apr 15, 2015 at 21:00

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! yeah i forgot to take that Mask function out and replace with the one i declare in the method, but same thing essentially
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.