C Programming · Interview question

How do you set, clear, and toggle a single bit without affecting the others?

A strong answer

Build a mask with a 1 at the target position, 1u << n, then: set with OR, reg |= (1u << n), because OR-ing with 1 forces that bit high and OR-ing with 0 leaves the rest unchanged. Clear with AND-NOT, reg &= ~(1u << n), because ~(1u << n) is all ones except a zero at position n, and AND-ing with 1 preserves a bit while AND-ing with 0 forces it low. Toggle with XOR, reg ^= (1u << n), because XOR with 1 flips and XOR with 0 preserves. Each idiom touches exactly the target bit and leaves every other bit alone, which is essential when a register packs many independent controls. The u suffix keeps the mask unsigned to avoid signed-shift UB.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Bit Manipulation & Masks

Set, clear, toggle, and test individual bits without disturbing their neighbors: the read-modify-write idioms behind every GPIO and peripheral driver.

More Bit Manipulation & Masks questions

Browse all 472 interview questions