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.
C Programming · Interview question
How do you set, clear, and toggle a single bit without affecting the others?
A strong answer
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
What's the difference between GPIOA->ODR |= (1u << 5) and GPIOA->ODR = (1u << 5)?Why should you write 1u << n instead of 1 << n for a mask?Your code reads a register field with if (reg & MASK == 0) and it never matches. Why?Is reg |= (1u << n) safe to use on a register that an interrupt also modifies?
Browse all 472 interview questions