Write a C program to input any number from user and clear the n

Input number: 13

Input nth bit to clear: 0

Output number after clearing nth bit: 12 (in decimal)

Happy coding ;)

^{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 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:

In previous two post I have already explained how to get and set n^{th}bit of any number. Here to clear n^{th}bit of a number we will use bitwise left shift <<, bitwise complement ~ and bitwise AND & operator. What we need to do is:- 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.

^{th}bit.### Program:

/** * C program to clear the 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 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)

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 ;)

### 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 toggle 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.

< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).