C program to clear nth bit of a number

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.

Required knowledge

Operators, Data Types in c, Variables in C, Basic input/output

Logic to clear nth bit of a number

To clear nth bit of a number we will use combination of 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 position to clear from user. Store it in some variable say num and n.

  2. Left shift 1, n times i.e. 1 << n.

  3. Perform bitwise complement with the above result. So that the nth bit becomes unset and rest of bit becomes set i.e. ~ (1 << n).

  4. Finally, perform bitwise AND operation with the above result and num. The above three steps together can be written as num & (~ (1 << n));

Let us take an example to understand this.

Clear nth bit of a number

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 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 * finally perform bitwise AND with num 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; }


Output:
Enter any number: 10 Enter nth bit to clear (0-31): 25 Bit cleared successfully. Number before clearing 25 bit: 10 (in decimal) Number after clearing 25 bit: 10 (in decimal) Process returned 0 (0x0) execution time : 11.510 s




Instagram