Bird
Raised Fist0

Identify the bug in the following code snippet that attempts to reverse bits of a 32-bit unsigned integer using a cache lookup:

medium🐞 Bug Identification Q7 of Q15
Bit Manipulation - Reverse Bits
Identify the bug in the following code snippet that attempts to reverse bits of a 32-bit unsigned integer using a cache lookup:
ANot masking final result to 32 bits
BLooping 4 times instead of 8 times
CNot masking byte with 0xff before cache lookup
DUsing signed right shift instead of unsigned
Step-by-Step Solution
Solution:
  1. Step 1: Analyze byte extraction

    Extracting byte uses (n >> (i*8)) & 0xff, which correctly masks the byte.
  2. Step 2: Check cache lookup

    If masking was missing, higher bits could leak, corrupting cache index.
  3. Step 3: Identify bug

    In this code, masking is present, so no bug there. The subtle bug is elsewhere.
  4. Step 4: Check loop and shifts

    Looping 4 times is correct for 32 bits; final masking is done implicitly.
  5. Step 5: Final bug

    The bug is not masking the final result to 32 bits after shifts, which can cause overflow.
  6. Final Answer:

    Option A -> Option A
  7. Quick Check:

    Final result should be masked to 32 bits to avoid overflow [OK]
Quick Trick: Always mask final result to 32 bits after shifts [OK]
Common Mistakes:
MISTAKES
  • Forgetting final mask
  • Incorrect loop count
  • Using signed shifts
Trap Explanation:
PITFALL
  • Candidates often overlook final masking, causing wrong results on large inputs.
Interviewer Note:
CONTEXT
  • Tests attention to detail in bitwise operations and masking.
Master "Reverse Bits" in Bit Manipulation

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bit Manipulation Quizzes