Write a C program to input any number from user and clear the nth bit of the given number using bitwise operator. How to clear nth bit of a given number using bitwise operator in C programming. How to unset (0) the value of nth bit of a given number in C.
Example
Input
Input number: 13 Input nth bit to clear: 0
Output
Number after clearing nth bit: 12 (in decimal)
Also read –
Required knowledge
Bitwise operators, Data types, Variables and Expressions, Basic input/output
Logic to clear nth bit of a number
To clear nth bit of a number we will use combination of bitwise left shift <<
, bitwise complement ~
and bitwise AND &
operator.
Below is the step by step descriptive logic to clear nth bit of a number.
- Input number and nth bit position to clear from user. Store it in some variable say num and n.
- Left shift 1, n times i.e.
1 << n
. - Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e.
~ (1 << n)
. - Finally, perform bitwise AND operation with the above result and num. The above three steps together can be written as
num & (~ (1 << n));
Let us take an example to understand this.
Program to clear nth bit of a number
/**
* C program to clear the 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 number you want to clear */
printf("Enter nth bit to clear (0-31): ");
scanf("%d", &n);
/*
* Left shifts 1 to n times
* Perform complement of above
* finally perform bitwise AND with num and result of above
*/
newNum = num & (~(1 << n));
printf("Bit cleared successfully.\n\n");
printf("Number before clearing %d bit: %d (in decimal)\n", n, num);
printf("Number after clearing %d bit: %d (in decimal)\n", n, newNum);
return 0;
}
Output
Enter any number: 13 Enter nth bit to clear (0-31): 0 Bit cleared successfully. Number before clearing 0 bit: 13 (in decimal) Number after clearing 0 bit: 12 (in decimal)
Happy coding 😉
Recommended posts
- Bitwise operator programming exercises index.
- C program to toggle nth bit of a number.
- C program to flip bits of a binary number using bitwise operator.
- C program to count trailing zeros in a binary number.
- C program to count leading zeros in a binary number.
- C program to count total zeros and ones in a binary number.