Bird
Raised Fist0

Given the following Python function for UTF-8 validation, what is the value of the variable remaining after processing the second byte in the input [197, 130, 1]?

easy🧾 Code Trace Q12 of Q15
Bit Manipulation - UTF-8 Validation
Given the following Python function for UTF-8 validation, what is the value of the variable remaining after processing the second byte in the input [197, 130, 1]?
def validUtf8(data):
    remaining = 0
    for byte in data:
        if remaining == 0:
            if (byte >> 5) == 0b110:
                remaining = 1
            elif (byte >> 4) == 0b1110:
                remaining = 2
            elif (byte >> 3) == 0b11110:
                remaining = 3
            elif (byte >> 7) == 0:
                remaining = 0
            else:
                return False
        else:
            if (byte >> 6) != 0b10:
                return False
            remaining -= 1
    return remaining == 0
A2
B0
C1
DFalse (function returns early)
Step-by-Step Solution
  1. Step 1: Trace first byte (197)

    197 in binary is 11000101. (197 >> 5) == 0b110, so remaining is set to 1.
  2. Step 2: Trace second byte (130)

    Since remaining is 1, check if (130 >> 6) == 0b10. 130 in binary is 10000010, so condition holds and remaining is decremented to 0.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Remaining after second byte is 1 -> decremented to 0 after processing second byte [OK]
Quick Trick: Check bit shifts and decrement continuation counter correctly [OK]
Common Mistakes:
MISTAKES
  • Off-by-one decrement of remaining
  • Misinterpreting bit shifts for continuation bytes
Trap Explanation:
PITFALL
  • Confusing when to decrement remaining or misreading bit patterns leads to wrong remaining count.
Interviewer Note:
CONTEXT
  • Tests candidate's ability to mentally execute bitwise code and track state.
Master "UTF-8 Validation" 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