Which bitwise operator is suitable for checking whether a particular bit is on or off?
Answer: B
Correct answer: & operator
Testing a bit means isolating it and discarding everything else, which is what AND with a single-bit mask does: n & (1 << k) is non-zero if bit \( k \) is set and zero if it is not.
Note that the non-zero result is \( 2^k \) rather than 1, so a comparison with 1 would fail for any bit but the lowest - test against zero, or shift the result down. The same operator serves for clearing bits, with an inverted mask; the difference is whether the result is stored back or merely tested.
Please log in or register to report this question.