Bit Manipulation - Reverse BitsIdentify 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 bitsBLooping 4 times instead of 8 timesCNot masking byte with 0xff before cache lookupDUsing signed right shift instead of unsignedCheck Answer
Step-by-Step SolutionSolution:Step 1: Analyze byte extractionExtracting byte uses (n >> (i*8)) & 0xff, which correctly masks the byte.Step 2: Check cache lookupIf masking was missing, higher bits could leak, corrupting cache index.Step 3: Identify bugIn this code, masking is present, so no bug there. The subtle bug is elsewhere.Step 4: Check loop and shiftsLooping 4 times is correct for 32 bits; final masking is done implicitly.Step 5: Final bugThe bug is not masking the final result to 32 bits after shifts, which can cause overflow.Final Answer:Option A -> Option AQuick 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:MISTAKESForgetting final maskIncorrect loop countUsing signed shiftsTrap Explanation:PITFALLCandidates often overlook final masking, causing wrong results on large inputs.Interviewer Note:CONTEXTTests attention to detail in bitwise operations and masking.
Master "Reverse Bits" in Bit Manipulation3 interactive learning modes - each teaches the same concept differentlyTry ItSolutionTrace
More Bit Manipulation Quizzes Bitwise AND of Numbers Range - Bitwise AND of Numbers Range - Quiz 6medium Counting Bits (0 to N) - Counting Bits (0 to N) - Quiz 4medium Find the Missing Number - Find the Missing Number - Quiz 5medium Generate All Permutations Using Bitmask DP - Generate All Permutations Using Bitmask DP - Quiz 12easy Gray Code - Gray Code - Quiz 1easy Maximum XOR of Two Numbers - Maximum XOR of Two Numbers - Quiz 6medium Number of 1 Bits (Hamming Weight) - Number of 1 Bits (Hamming Weight) - Quiz 12easy Single Number II (Three Copies) - Single Number II (Three Copies) - Quiz 9hard Sum of Two Integers Without + Operator - Sum of Two Integers Without + Operator - Quiz 9hard Sum of Two Integers Without + Operator - Sum of Two Integers Without + Operator - Quiz 5medium