Spread the love

To turn off the particular bit in given number we use bitwise ‘<<‘, ‘&’ and ‘~’ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k’th bit. If we do bitwise ‘&’ of this expression with n, we get a number which has all bits same as n except the k’th bit which is 0.

For Examples:

Input: n = 15, k = 1               
Output: 14

Explanation :- Binary Representation of 15 is 1111, if we turn off first bit then binary would be 1110 which is 14.

Input: n = 15, k = 2
Output: 13

Explanation :- Binary Representation of 15 is 1111, if we turn off first bit then binary would be 1101 which is 14.

 

#include<stdio.h>
 
// Returns a number that has all bits same 
// except the bit which is made 0
int TurnOffParticularBit(int number, int bit)
{
    // bit must be greater than 0
    if (bit <= 0) return number;
 
    // Do & of number with a number with all set bits except
    // the bit
    return (number & ~(1 << (bit - 1)));
}
 
int main()
{
     printf("%d",TurnOffParticularBit(15, 4)  );

     return 0;
}

 

If you like this Article, then don’t forget to Click on Social likes buttons.