VOOZH about

URL: https://www.geeksforgeeks.org/c/clearing-bits-in-c/

⇱ Clearing Bits in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Clearing Bits in C

Last Updated : 10 Jul, 2024

In C programming, clearing a bit is the process of setting a specific bit of the binary number to 0. This operation is crucial in various applications, including memory management, data processing, and hardware control.

In this article, we will learn how to clear a bit at a given position in a binary number. We will also explore how to clear multiple bits simultaneously.

How to Clear a Bit in C?

Clearing a bit means setting its value to 0. In C, we can clear a given bit using the AND operator (&) combined with a bit mask. Below is the truth table of AND:

👁 Truth-Table-for-AND-Operation

From the above table, we can infer that

  • By ANDing a bit with 0, the given bit is cleared (set to 0).
  • By ANDing a bit with 1, the given bit remains unchanged.

Clearing a Specific Bit in C

To clear a specific bit in a number, you can use a bit mask with the AND operator. In that bitmask number, only the bit you want to clear is set to 0, and all other bits are set to 1.

Example:

Input:
binary_number: 01100111
bit to clear: 5th

Output:
binary_number: 01100111
mask_used: 11011111

We can use the left shift operator with NOT operator to create a mask but remember the 0-based indexing in the shifting.


Output
Result: 103

Time Complexity: O(1)
Space Complexity: O(1)

Clearing Multiple Bits in C

We can also clear multiple bits by creating a mask with multiple bits set to 0. ANDing the number with this mask will clear all corresponding bits.

Example: Clearing the 1st, 3rd, and 4th Bits


Output
Result: 98

Time Complexity: O(n), where n is the number of bits to be cleared.
Space Complexity: O(1)



Comment
Article Tags: