Understanding the bitwise AND (&) operator in C#: which uses are correct? 1) Invert a bit 2) Put a bit ON (set to 1) 3) Put a bit OFF (clear to 0) 4) Check whether a bit is ON 5) Check whether a bit is OFF

Difficulty: Easy

Correct Answer: 3, 4, 5

Explanation:


Introduction / Context:
Bitwise AND (&) is frequently used with masks for clearing and testing bits. This question asks which operations are appropriate for &.



Given Data / Assumptions:

  • We have integer/byte values and masks.
  • We want to categorize valid uses of &.


Concept / Approach:
AND with a mask of 0 clears a bit; with 1, it preserves the bit. Therefore, & can clear bits and test bits. It cannot invert or set bits to 1; those operations are best done with XOR (^) for invert and OR (|) for setting.



Step-by-Step Solution:

To put a bit OFF (clear): n = n & ~mask → option 3 is valid.To check if bit is ON: (n & mask) == mask → option 4 is valid.To check if bit is OFF: (n & mask) == 0 → option 5 is valid.


Verification / Alternative check:
Example: n = 0b1011 (11), mask = 0b1000 (8). n & mask = 8 (bit ON). Clearing: n & ~mask = 0b0011.



Why Other Options Are Wrong:

  • 1: Inversion requires XOR (^) with mask or bitwise NOT (~) on the whole value, not &.
  • 2: Setting a bit ON uses OR (|) with the mask.


Common Pitfalls:
Using & when you actually want to set bits ON (use |) or invert (use ^ or ~ appropriately).



Final Answer:
3, 4, 5

Discussion & Comments

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