Write a C program to input any number from user and clear the n^{th} bit of the given number using bitwise operator. How to clear n^{th} bit of a given number using bitwise operator in C programming. How to unset (0) the value of n^{th} 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)

## Required knowledge

Basic C programming, Bitwise operator

## Logic to clear nth bit of a number

In previous two post I explained to get and set n^{th} bit of a number.

To clear n^{th} bit of a number we will use 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 to clear from user. Store it in some variable say num and n.
- Left shift << 1(in decimal) to
`n`

times (where`n`

is the bit number to be cleared). - Perform bitwise complement ~ operation with the above result so that the n
^{th}bit becomes unset and rest of bit becomes set. - Now perform bitwise AND & operation with the above result and the number to get all set bits except the n
^{th}bit.

In general perform number & (~(1 << n)) to clear the n^{th} bit.

## 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 a 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
* then perform bitwise AND with number 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;
}
```

**Note:** Here I have assumed that bit ordering starts from 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 😉

<pre><code> ----Your Source Code---- </code></pre>