![]() |
VOOZH | about |
In C++ programming, clearing a bit involves setting the value of a specific bit in a binary number to 0. This operation is useful in various applications such as bit masking, controlling hardware, and optimizing algorithms. Bit clearing involves setting the value of a bit to 0. For example:
In C++, we can use the along with the to clear bits. The AND operator outputs true or 1 only when both input bits are 1, while the NOT operator inverts the bit values. The truth table for bitwise AND(&) and NOT(~) is as follows:
A | B | A & B | ~(A & B) |
|---|---|---|---|
0 | 0 | 0 | 1 |
0 | 1 | 0 | 1 |
1 | 0 | 0 | 1 |
1 | 1 | 1 | 0 |
To clear a specific bit in a number, we can create a bitmask with the bit to be cleared set to 0, and all other bits set to 1. We then use the AND operator to clear the bit.
Example: The below example demonstrates how we can clear a specific bit, i.e., the 3rd bit in a number.
Result: 25
Explanation:
We can also clear multiple bits at once by creating a bitmask where all bits we want to clear are set to 0. AND the number with this mask to clear the corresponding bits.
Example: The below example demonstrates how we can clear multiple bits, i.e., 1st, 3rd, and 4th bits in a number.
Result: 16
Explanation: