Difficulty: Easy
Correct Answer: Yes — x = x & ~mask clears the bits that are 1 in mask
Explanation:
Introduction / Context:
Clearing bits is the counterpart to setting bits. It is used in configuration registers, permission systems, and toggling flags off. The standard pattern leverages bitwise NOT to invert a mask and then AND to force target positions to 0.
Given Data / Assumptions:
Concept / Approach:
Bitwise NOT (~mask) flips 1s to 0s and 0s to 1s. When we AND x with ~mask, any positions where mask had 1 become 0 in the result (since 0 & anything = 0). All other positions pass through unchanged (1 & bit = bit). This reliably clears the selected bits regardless of their prior state.
Step-by-Step Solution:
Verification / Alternative check:
Example: x=0b1111, mask=0b0101 → ~mask=0b1010 → x & ~mask = 0b1010, clearing bits 0 and 2 as intended.
Why Other Options Are Wrong:
Common Pitfalls:
Building the mask incorrectly; using XOR when you meant to clear; forgetting parentheses in complex expressions.
Final Answer:
Yes — x = x & ~mask clears the bits that are 1 in mask.
Discussion & Comments