Quantcast
Channel: Codeforwin
Viewing all articles
Browse latest Browse all 132

C program to clear nth bit of a number

$
0
0
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 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 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:
  1. Left shift << 1(in decimal) to n times (where n is the bit number to be cleared).
  2. Perform bitwise complement ~ operation with the above result so that the nth bit becomes unset and rest of bit becomes set.
  3. Now perform bitwise AND & operation with the above result and the number to get all set bits except the nth bit.
Or in general perform number & (~(1 << n)) to clear 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
X
_
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 ;)



Viewing all articles
Browse latest Browse all 132

Trending Articles