toggle or invert nth bit

1. read a number x and position n
2. Left shift 1 to n times, i.e. 1 << n.
3. Perform bitwise XOR with x and result evaluated above
  i.e. x ^ (1 << n);

To toggle a bit we will use bitwise XOR ^ operator. Bitwise XOR operator evaluates to 1 if corresponding bit of both operands are different otherwise evaluates to 0.
For example - if Least Significant Bit of num is 1, then num ^ 1 will make LSB of num to 0. And if LSB of num is 0, then num ^ 1 will toggle LSB to 1.

Program

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

Input:
30 2
Output:
Number before toggle 30
Number after toggle 26

No comments:

Post a Comment