Clear nth bit of a number

To clear nth bit of a number we will use combination of bitwise left shift <<, bitwise complement ~ and bitwise AND & operator.
1. read a number x and position n
2. Left shift 1, n times i.e. 1 << n.
3. Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. ~ (1 << n).
4. Finally, perform bitwise AND operation with the above result and x.
The above three steps together can be written as x& (~ (1 << n));


#include<stdio.h>
int main() {
    int n,x,num;
    scanf("%d%d",&x,&n);
    num = x & (~(1 << n));
    printf("Number before clearing %d\n",x);
    printf("Number after clearing %d",num);
return 0; 
}

Input:
22 1
Output:
Number before clearing 22
Number after clearing 20

No comments:

Post a Comment