C# bit test (Byte): check whether the 4th bit from the right (value 8) is ON. Which condition is correct?

Difficulty: Easy

Correct Answer: if ((n & 8) == 8) Console.WriteLine('Fourth bit is ON');

Explanation:


Introduction / Context:
Testing whether a particular bit is set is a standard bitwise task. Here we need to test the 4th bit from the right (value 8) of a byte variable n.



Given Data / Assumptions:

  • n is byte.
  • Target bit is the 4th from the right (1-based), value 8.
  • We must write a correct if-condition and message.


Concept / Approach:
To test if a bit is ON, AND the value with a mask that has 1 at that bit. If the result equals the mask, the bit is set. Therefore, use mask 8 and compare with 8.



Step-by-Step Solution:

Mask = 8.Compute (n & 8).Check equality with 8 → if true, bit is ON.


Verification / Alternative check:
Try n = 13 (00001101). (n & 8) == 8 is true; try n = 5 (00000101), also true; try n = 1, false.



Why Other Options Are Wrong:

  • A: Uses 16, which targets the 5th bit.
  • C: Uses the invalid operator ! with a number.
  • D: XOR comparison equals 8 only for specific values; it is not a generic bit test.
  • E: ~ is bitwise complement; expression is invalid and meaningless for this test.


Common Pitfalls:
Mixing up XOR and AND for bit testing; confusing 0-based with 1-based bit positions.



Final Answer:
if ((n & 8) == 8) Console.WriteLine('Fourth bit is ON');

Discussion & Comments

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