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:
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.
C
// C Program to Clear a given bit of a binary number
#include <stdio.h>
int main()
{
// Binary: 01100111
unsigned int num = 103;
// Clearing the 5th bit (0-based index)
unsigned int bit_position = 4;
// Create a mask with only the 5th bit set to 0
unsigned int mask = ~(1 << bit_position);
// Clear the bit using AND
num = num & mask;
// Print the result
printf("Result: %u\n", num);
return 0;
}
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
C
// C Program to Clear multiple bits of a binary number
#include <stdio.h>
int main()
{
// Binary: 01100111
unsigned int num = 103;
// Create a mask with the 1st, 3rd, and 4th bits set to
// 0
unsigned int mask = ~((1 << 0) | (1 << 2) | (1 << 3));
// Clear the bits using AND
num = num & mask;
// Print the result
printf("Result: %u\n", num);
return 0;
}
Time Complexity: O(n), where n is the number of bits to be cleared.
Space Complexity: O(1)