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\invert\flip 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.



Input number: 22
Input nth bit to toggle: 1


After toggling nth bit: 20 (in decimal)

Required knowledge

Basic C programming, Bitwise operator

Logic to toggle nth bit of a number

In previous posts I explained to get, set or clear nth bit of a number using bitwise operators. Here we will learn to toggle nth bit of a number.

Toggling bit means setting the value of the bit in its complement state. Means if the bit is currently in set(1) state then change it to unset(0) state else if the bit is in unset(0) state then change it to set(1) state. Below is the step by step descriptive logic to toggle nth bit of a number.

  1. Read number and n bit number which is to be toggled. Store it in some variable say number and n.
  2. Right shift << 1 (in decimal) to n times.
  3. Perform bitwise XOR ^ operation with the result evaluated above.

In general you need to perform number ^ (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 the bit number you want to toggle
    printf("Enter nth bit to toggle (0-31): ");
    scanf("%d", &n);

     * Left shifts 1 to n times
     * then perform bitwise XOR with number and result of above
    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;

Note: I have assumed that bit ordering starts from 0.


Enter any number: 22
Enter nth bit to toggle (0-31): 1
Bit toggled successfully.

Number before toggling 1 bit: 22 (in decimal)
Number after toggling 1 bit: 20 (in decimal)

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>