C program to toggle or invert nth bit of a number

C program to toggle or invert nth bit of a number

Write a C program to input any number from user and toggle or invert or flip nth bit of the given number using bitwise operator. How to toggle nth bit of a given number using bitwise operator in C programming. C program set nth bit of a given number if it is unset otherwise unset if it is set.

Required knowledge

Operators, Data Types in c, Variables in C, Basic input/output

Logic to toggle nth bit of a number

Toggling bit means setting a bit in its complement state. Means if bit is currently set then change it to unset and vice versa.

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. We will use this ability of bitwise XOR operator to toggle a bit. 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.

Step by step descriptive logic to toggle nth bit of a number.

  1. Input number and nth bit position to toggle from user. Store it in some variable say num and n.

  2. Left shift 1 to n times, i.e. 1 << n.

  3. Perform bitwise XOR with num and result evaluated above i.e. num ^ (1 << n);.

Program to toggle or invert nth bit

/** * C program to toggle nth bit of a number */ #include <stdio.h> int main() { int num, n, newNum; /* Input number from user */ printf("Enter any number: "); scanf("%d", &num); /* Input bit position you want to toggle */ printf("Enter nth bit to toggle (0-31): "); scanf("%d", &n); /* * Left shifts 1, n times * then perform bitwise XOR with num */ newNum = num ^ (1 << n); printf("Bit toggled successfully.\n\n"); printf("Number before toggling %d bit: %d (in decimal)\n", n, num); printf("Number after toggling %d bit: %d (in decimal)\n", n, newNum); return 0; }


Output:
Enter any number: 10 Enter nth bit to toggle (0-31): 20 Bit toggled successfully. Number before toggling 20 bit: 10 (in decimal) Number after toggling 20 bit: 1048586 (in decimal) Process returned 0 (0x0) execution time : 13.799 s




Instagram