C program to clear nth bit of a number

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)

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 nth bit of a number.

To clear nth 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.

  1. Input number and nth bit to clear from user. Store it in some variable say num and n.
  2. Left shift << 1(in decimal) to n times (where n is the bit number to be cleared).
  3. Perform bitwise complement ~ operation with the above result so that the nth bit becomes unset and rest of bit becomes set.
  4. Now perform bitwise AND & operation with the above result and the number to get all set bits except the nth bit.

In general perform number & (~(1 << n)) to clear the nth 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 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>