Using bitwise AND (&) with a mask to test whether a specific bit is set in an integer: is this a valid and standard technique?

Difficulty: Easy

Correct Answer: Correct

Explanation:


Introduction / Context:
Testing individual bits is a foundational skill in systems programming, device drivers, embedded development, and competitive programming. The classic approach is to use the bitwise AND operator with a mask that has the target bit set to 1 and all other bits 0.


Given Data / Assumptions:

  • x is an integer value.
  • mask is an integer with a 1 in the bit position we want to test and 0 elsewhere (e.g., 1u << k).
  • We want a boolean-like result indicating whether the bit is set.


Concept / Approach:
The expression (x & mask) != 0 evaluates to true if and only if the corresponding bit in x is 1. This works because AND preserves a 1 only where both operands have a 1. It is completely independent of endianness, as endianness affects byte ordering in memory, not the logical interpretation of bit positions within an arithmetic expression.


Step-by-Step Solution:

Construct mask = 1u << k to target bit k.Compute test = x & mask.If test != 0, the kth bit is set; otherwise it is clear.


Verification / Alternative check:
For x = 10 (1010b) and k = 1, mask = 0010b; x & mask = 0010b != 0 → bit 1 is set. For k = 0, mask = 0001b; x & mask = 0000b → bit 0 is not set.


Why Other Options Are Wrong:

Incorrect: This is a standard technique.Valid only for powers-of-two masks: Any mask that isolates desired bits works; a single-bit mask is indeed a power of two, but the approach is general.Endianness: Not relevant to bitwise evaluation.Requires multiplication/division: Unnecessary; bitwise AND is sufficient.


Common Pitfalls:
Using signed shifts incorrectly; forgetting to use unsigned types when shifting to build masks.


Final Answer:
Correct.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion