Topics / Embedded C / Q10
How do you set, clear, toggle and test a bit in a register?
Short answer: Build a single-bit mask with 1u << n, then OR it to set, AND with its complement to clear, XOR to toggle, and AND to test. For multi-bit fields, clear the field with an inverted mask and OR in the new value.
reg |= (1u << n); /* set bit n */
reg &= ~(1u << n); /* clear bit n */
reg ^= (1u << n); /* toggle bit n */
if (reg & (1u << n)) { } /* test bit n (non-zero if set) */
bool b = (reg >> n) & 1u; /* bit n as 0 or 1 */
/* multi-bit field: e.g. bits 5..4 = mode */
#define MODE_Pos 4u
#define MODE_Msk (3u << MODE_Pos)
reg = (reg & ~MODE_Msk) | ((mode << MODE_Pos) & MODE_Msk);
Why 1u: 1 << 31 shifts into the sign bit of a signed int, which is undefined behaviour (before C23). With 1u the shift is unsigned and well-defined.
On real hardware, prefer hardware set/clear registers when the peripheral has them:
GPIOA->BSRR = (1u << 5); /* set PA5 atomically (STM32) */
GPIOA->BSRR = (1u << (5 + 16)); /* reset PA5 atomically */
NRF_P0->OUTSET = (1u << 13); /* nRF52: separate SET/CLR registers */
A single write cannot be corrupted by an interrupt, unlike |= (read-modify-write).
Registers that behave differently
- Write-1-to-clear (W1C) status flags: clear a flag by writing a 1 only to that bit (
SR = FLAG;), notSR |= FLAG;, which would clear every pending flag. - Read-to-clear registers: reading them for a test also clears them.
- Write-only registers (e.g.
BSRR): reading returns 0 or garbage, so|=does not work.
Always check the reference manual's access type (rw, r, w, rc_w1, rc_r).