Bit masking and shifts in C: evaluate the expression and print the result. #include<stdio.h> int main() { unsigned int res; res = (64 >>(2 + 1 - 2)) & (~(1 << 2)); printf("%d ", res); return 0; }

Difficulty: Easy

Correct Answer: 32

Explanation:

Introduction / Context:This exercise evaluates operator precedence, arithmetic inside shift counts, and bit masking using complement and bitwise AND. It is a classic quick check of bit-twiddling fluency.

Given Data / Assumptions:

  • All operations occur on unsigned int.
  • 64 in binary is 1 at bit 6 (counting from bit 0), i.e., 0b0100 0000.
  • 1 << 2 is 4, whose binary has only bit 2 set.

Concept / Approach:We first evaluate the shift count: 2 + 1 - 2 = 1, so the right shift is by 1. Then we apply a mask that clears bit 2 and preserves all others via bitwise NOT of 4. Finally, we AND the shifted value with that mask.

Step-by-Step Solution:Compute shift count: 2 + 1 - 2 = 1.Shift: 64 >> 1 = 32 (binary 0b0010 0000).Form mask: ~(1 << 2) = ~4. In binary, this is all ones except bit 2 is zero.AND: 32 & ~4 = 32 because bit 2 of 32 is not set.printf prints 32.

Verification / Alternative check:Write the numbers in binary to see that only bit 5 is set after shifting, while the mask only clears bit 2, leaving 32 unaffected.

Why Other Options Are Wrong:64 would require no shift. 0 or 28 would require clearing bit 5, which the mask does not do. 128 would require a left shift or a different starting value.

Common Pitfalls:Miscounting shift precedence vs addition/subtraction; forgetting that ~ affects all bits, not just the low nibble; confusing decimal with binary positions.

Final Answer:32

More Questions from Bitwise Operators

Discussion & Comments

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