C / C++ FAQs & Programming Resources - ProkutFAQ : BitSetUnset

HomePage Recent Changes Recently Commented Login/Register
Quick Links
Categories
Links

How to set or unset a particular bit in a number?


This requires understanding the bitwise operators. We will be using two operators here | (or) and ^(exclusive or).

When we or an integer type with another integer type, the or operation is executed on the corresponding bits of each number. The first bits of both the numbers are ored with one another. The second bits are ored with one another and so on. When either or both of the bits are 1 then the output is 1. It is zero otherwise.

Exclusive or (xor) on the other hand produces an output 1 only when the bits to be xor'ed are different. The output is 0 otherwise.

Now say we want to set the MSB of a given number to 1. Let the given number be 5 whose bit pattern is 00000101. For simplicity let us assume that a character on this particular machine is 8 bits long. Now we can easily see that if we or the MSB bit of this number with 1 we can change that bit to 1. But at the same time we will have to ensure that the other bits are not changed. To do this we can or the MSB with 1 and or the rest of the bits with 0 to preserve the bit pattern. Now how do we generate a number which has 1 in MSB and all zeroes after that?

We can use the shift operator for that. (1<7) will give us a number with the bit-pattern 10000000. Now if we or this number with 5 (00000101) we get 10000101. So we have changed the MSB bit to 1.

0 0 0 0 0 1 0 1
(or with)
1 0 0 0 0 0 0 0
=

1 0 0 0 0 1 0 1


Now how do we set the MSB back to zero without changing the other bits? We can easily do this by xor'ing the output with (1<7) again.

1 0 0 0 0 1 0 1
(xor with)
1 0 0 0 0 0 0 0
=

0 0 0 0 0 1 0 1


Xor'ing with zero doesnt change the bits and hence has no effect on the bit pattern.

The following code uses this concept to set or unset a particular bit in a given number.

     #include <iostream>
     int main(){
         int num=21; //binary representation is 10101
         //say we want to set the 2nd bit from right
         int k=1;
         k<<=1; //binary representation of k will now be 0010.
         num|=k; //num will now be 10111
         //now say we want to unset the 2nd bit again
         num^=k;//num will now again become 10101
         //to set the n-th bit
         int n;
         std::cin>>n;
         k=1;
         k<<=(n-1);
         num|=k; //this would set the n-th bit
         //to unset xor
         num^=k; //this will unset the n-th bit
     }


Alternatively we can use the bitset class provided in the STL. It has member function set and unset to set or unset a particular bit.
 Comments [Hide comments/form]
Page was generated in 0.0272 seconds