Write a C program to input any number from user and toggle 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.
Example:
Input number: 22
Input nth bit to toggle: 1
Output after toggling nth bit: 20 (in decimal)
Happy coding ;)
Example:
Input number: 22
Input nth bit to toggle: 1
Output after toggling nth bit: 20 (in decimal)
Required knowledge:
Basic C programming, Bitwise operatorToggling 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.Logic:
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:- Right shift << 1 (in decimal) to n times.
- Perform bitwise XOR ^ operation with the result evaluated above.
Program:
/**
* 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.
Output
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)
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
- Bitwise operator programming exercises index.
- C program to get nth bit of a number.
- C program to set nth bit of a number.
- C program to clear nth bit of a number.
- C program to get highest set bit of a number.
- C program to get lowest set bit of a number.
- C program to count trailing zeros in a binary number.
- C program to count leading zeros in a binary number.
- C program to flip bits of a binary number using bitwise operator.
- C program to total number of zeros and ones in a binary number.
- C program to convert decimal to binary number system using bitwise operator.
- C program to swap two numbers using bitwise operator.
- C program to check whether a number is even or odd using bitwise operator.
- C program to find first and last digits of any number.