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
Output after toggling nth bit: 20 (in decimal)

Required knowledge:

Basic C programming, Bitwise operator

Toggling bit

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.


In previous posts I explained how to get, set or clear nth bit of a number using bitwise operators. To toggle nth bit of a number what you need to do is:
  1. Right shift << 1 (in decimal) to n times.
  2. Perform bitwise XOR ^ operation with the result evaluated above.
Or in general you have 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;

    //Reads a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    //Reads 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: Here 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 ;)

You may also like

Labels: , ,