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 operatorLogic:
In previous two post I have already explained how to get and set nth bit of any number. Here to clear nth 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 nth 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 nth 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.