Bit operations in C# (Byte): turn OFF the 4th bit from the right (bit value 8) without changing other bits. Which statement performs this correctly?

Difficulty: Easy

Correct Answer: n = n & 0xF7

Explanation:


Introduction / Context:
In C# bit manipulation, clearing (turning OFF) a specific bit in a byte is a common task. This question checks whether you can choose the correct bit-mask and operator to clear the 4th bit from the right (counting 1, 2, 3, 4 → value 8) without disturbing other bits.



Given Data / Assumptions:

  • n is of type byte (0–255).
  • We must clear the 4th bit (value 8) and keep all other bits unchanged.
  • We are using C#'s bitwise operators with hexadecimal masks.


Concept / Approach:
To turn OFF a single bit, AND the value with a mask that has 0 in the target position and 1s elsewhere. For the 4th bit (value 8), the mask is 11110111 in binary, which is 0xF7 in hex. The operation is: n = n & 0xF7



Step-by-Step Solution:

Desired mask: all 1s except the 4th bit → 0xF7.Apply bitwise AND: n = n & 0xF7.All other bits remain as-is; only the 4th bit becomes 0.


Verification / Alternative check:
Try n = 0xFF (255). After n & 0xF7, result is 0xF7 (247), confirming only that bit was cleared.



Why Other Options Are Wrong:

  • A: && is a Boolean operator, not bitwise.
  • B: & 16 clears the 5th bit (value 16), not the 4th.
  • D: HexF7 is not valid C# syntax.
  • E: n = n & 8 zeroes every other bit, not just the 4th.


Common Pitfalls:
Confusing Boolean operators (&&, ||) with bitwise (&, |), and miscounting bit positions (remember that the 4th bit from the right has value 8).



Final Answer:
n = n & 0xF7

Discussion & Comments

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