Microcontroller peripherals are controlled through registers, and most registers pack many independent settings into one word. One bit enables a peripheral, two bits select a pin’s mode, four bits pick a clock divider. Changing one setting without disturbing the others is the core skill of register-level programming. In C, you do it with a handful of bitwise operators.
The four basic operations
| Goal | Operation | Idiom | Effect on other bits |
|---|---|---|---|
| Set bit n | OR with a mask | reg |= (1u << n); |
Unchanged |
| Clear bit n | AND with an inverted mask | reg &= ~(1u << n); |
Unchanged |
| Toggle bit n | XOR with a mask | reg ^= (1u << n); |
Unchanged |
| Test bit n | AND with a mask | if (reg & (1u << n)) |
Not modified |
The logic behind these:
x | 1is always 1 andx | 0isx, so OR sets only the bits that are 1 in the mask.x & 0is always 0 andx & 1isx, so AND with an inverted mask clears only the masked bits.x ^ 1flipsxandx ^ 0leaves it alone, so XOR toggles only the masked bits.
Setting, clearing, toggling and testing in code
#include <stdint.h>
#include <stdbool.h>
#define LED_PIN 5u
volatile uint32_t *const gpio_odr = (volatile uint32_t *)0x40020014u; /* STM32F4 GPIOA ODR */
void led_on(void) { *gpio_odr |= (1u << LED_PIN); }
void led_off(void) { *gpio_odr &= ~(1u << LED_PIN); }
void led_toggle(void) { *gpio_odr ^= (1u << LED_PIN); }
bool led_is_on(void) { return (*gpio_odr & (1u << LED_PIN)) != 0u; }
You can set or clear several bits at once by combining masks:
reg |= (1u << 3) | (1u << 7); /* set bits 3 and 7 */
reg &= ~((1u << 3) | (1u << 7)); /* clear bits 3 and 7 */
Note the extra parentheses when you clear several bits. ~ has to apply to the whole combined mask.
The register is accessed through a volatile pointer so the compiler performs every read and write. See the volatile keyword in embedded C for why.
Why 1u and fixed-width types matter
Small details in these expressions cause real bugs:
- Use unsigned constants.
1 << 31shifts a 1 into the sign bit of a signedint, which is undefined behavior in C. Write1u << 31, orUINT32_C(1) << 31to be explicit about the width. - Watch the width of
int. On 8-bit AVR,intis 16 bits, so1 << 20is undefined there. Use1UL << 20(at least 32 bits) orUINT32_C(1) << 20. - Don’t shift by the type’s width or more.
x << 32on a 32-bit value is undefined. Watch out for this in macros that compute shift amounts. - Expect integer promotion. Anything smaller than
intis promoted tointbefore bitwise operations. Withuint8_t m = 0x0F;, the expression~mis theintvalue0xFFFFFFF0on a 32-bit target. Assigning the result back to auint8_tgives the expected0xF0, but comparisons on the unassigned result can surprise you. Casting to the intended type ((uint8_t)~m) makes the intent clear.
Working with multi-bit fields
Many settings span several bits. On STM32, for example, each pin’s mode in the GPIOx->MODER register is a 2-bit field: 00 input, 01 output, 10 alternate function, 11 analog. Pin 5’s field sits at bits 10–11.
Writing a field
You can’t just OR a new value in, because any 1 bits already in the field would remain. Clear the field first, then set the new value:
uint32_t moder = GPIOA->MODER;
moder &= ~(3u << (5u * 2u)); /* clear the 2-bit field for pin 5 */
moder |= (1u << (5u * 2u)); /* write 01 = output */
GPIOA->MODER = moder;
Reading into a local, changing it, and writing it back once avoids an intermediate state where the field is temporarily 00, which can matter for some registers. It also means one volatile write instead of two.
Reading a field
Shift the field down and mask it:
uint32_t mode = (GPIOA->MODER >> (5u * 2u)) & 3u; /* 0..3 */
Helper macros and inline functions
Generic helpers reduce mistakes:
#define BIT(n) (1UL << (n))
static inline uint32_t field_get(uint32_t reg, uint32_t mask, unsigned shift)
{
return (reg >> shift) & mask;
}
static inline uint32_t field_set(uint32_t reg, uint32_t mask, unsigned shift, uint32_t value)
{
return (reg & ~(mask << shift)) | ((value & mask) << shift);
}
/* usage */
GPIOA->MODER = field_set(GPIOA->MODER, 3u, 10u, 1u); /* pin 5 -> output */
Inline functions give you type checking and evaluate each argument exactly once. If you write macros, wrap every argument and the whole expression in parentheses, because BIT(n + 1) must expand to (1UL << ((n + 1))), not something with different precedence.
Using the vendor’s bit definitions
Hard-coded shift numbers are easy to get wrong. Vendor device headers define names for most bits and fields. CMSIS-style headers commonly provide _Pos (bit position) and _Msk (mask already shifted into place) definitions, and a plain name that equals the mask:
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN; /* enable GPIOA clock */
USART2->CR1 |= USART_CR1_UE; /* enable the USART */
if (USART2->SR & USART_SR_TXE) { /* transmit register empty? */
USART2->DR = 'A';
}
Exact naming varies by vendor and chip family, so check the header for your part. Using these names makes code far easier to compare against the reference manual.
Read-modify-write traps
reg |= mask looks like one operation, but it’s three: read the register, modify the value, write it back. That has consequences.
An interrupt in the middle
If an interrupt handler modifies the same register or variable between the read and the write, main code writes back the stale value and undoes the handler’s change. For example, main code sets bit 3 of a GPIO output register while an ISR toggles bit 7. If the ISR runs between main’s read and write, the toggle is lost.
Fixes:
- Briefly disable interrupts around the read-modify-write.
- Use hardware atomic set/clear registers (see below).
- Design so that only one context ever writes a given register.
The ISR guide shows how to write short critical sections correctly.
Write-1-to-clear flags
Many status registers clear a flag when you write 1 to it, and ignore writes of 0. That’s common for interrupt-pending registers. Here |= is dangerous:
EXTI->PR |= EXTI_PR_PR0; /* WRONG: reads all pending bits and writes them all back as 1 */
EXTI->PR = EXTI_PR_PR0; /* RIGHT: clears only line 0 */
The |= version reads every pending flag and writes them all back as 1s, clearing interrupts you haven’t handled yet. For write-1-to-clear registers, always write the mask with plain =.
Some registers instead clear flags when you read them, or when you read the status register and then the data register. Read the “how to clear” note for each flag in the reference manual.
Registers that don’t read back what you wrote
Some registers behave differently on read and write. On many AVR chips, including the ATmega328P, writing a 1 to a bit in PINx toggles the matching PORTx bit. Reading PINx returns the pin levels. A PINB |= (1 << 5) would read the levels of all pins and toggle every pin that happened to read high. The correct form is PINB = (1 << 5);.
Write-only registers often read back as zero, so a read-modify-write on them silently clears every other setting. When the datasheet marks a register write-only, keep a shadow copy in RAM and write the full value.
Atomic set and reset registers
To avoid read-modify-write races entirely, many microcontrollers provide registers where writing a 1 sets or clears a bit and writing 0 does nothing.
On STM32, GPIOx->BSRR sets output bits with its lower 16 bits and resets them with its upper 16 bits:
GPIOA->BSRR = (1u << 5); /* PA5 high */
GPIOA->BSRR = (1u << (5u + 16u)); /* PA5 low */
Because each is a single write, an interrupt can’t corrupt it, and no other pin is affected. Other families offer similar features. Microchip SAM parts have OUTSET, OUTCLR and OUTTGL registers. The RP2040 provides atomic set, clear and XOR alias addresses for its peripheral registers. Some Cortex-M3 and M4 chips implement bit-banding, which maps each bit of certain memory regions to its own word address. Bit-banding is optional and absent from many cores, including Cortex-M0 and M7.
Why many developers avoid bitfields for registers
C lets you declare struct members with explicit bit widths:
struct ctrl {
uint32_t enable : 1;
uint32_t mode : 2;
uint32_t div : 4;
};
This reads nicely, but the C standard leaves much of the layout implementation-defined. That includes bit order within a storage unit, how fields straddle boundaries, and even which base types are allowed. The size and type of the memory access the compiler generates may also not match what the hardware needs. Some vendor headers do use bitfields with a specific compiler in mind, but for portable register code, masks and shifts are more predictable. Bitfields are fine for packing data in RAM when you don’t care about the exact layout.
Handy bit tricks
For unsigned integers:
| Task | Expression |
|---|---|
Is x a power of two? |
x != 0 && (x & (x - 1)) == 0 |
| Clear the lowest set bit | x &= x - 1 |
| Isolate the lowest set bit | x & (~x + 1) |
| Mask of the lowest n bits (n < width) | (1u << n) - 1u |
Round x up to a multiple of a power of two a |
(x + a - 1u) & ~(a - 1u) |
| Count set bits (GCC/Clang) | __builtin_popcount(x) |
| Count leading zeros (GCC/Clang, x != 0) | __builtin_clz(x) |
| Swap byte order of 32 bits (GCC/Clang) | __builtin_bswap32(x) |
On Arm, __builtin_clz compiles to the single CLZ instruction on cores that have it (Cortex-M3 and higher). Bit-reversal and similar operations are also available as CMSIS intrinsics, such as __RBIT().
Writing binary constants
Binary literals such as 0b1010 were a GCC and Clang extension in C until C23 made them standard. They’re widely supported by embedded compilers but may not be accepted under strict older-standard settings. Hex is the traditional choice. Each hex digit is exactly four bits, so 0xF0 reads directly as “upper four bits set”. Shifts of named bit positions (1u << UART_EN_BIT) are usually clearest of all.
Checklist
- Use
|=to set,&= ~to clear,^=to toggle,&to test - Use unsigned, correctly sized constants (
1u,1UL,UINT32_C(1)) - Clear a multi-bit field before writing its new value
- Prefer vendor bit names over magic numbers
- Never
|=a write-1-to-clear register; use= - Protect read-modify-writes that an ISR can interrupt, or use atomic set/reset registers
- Check whether each register is readable, write-only or has side effects on read
- Prefer masks and shifts to bitfields for hardware registers
These idioms show up everywhere in firmware, from a bare-metal STM32 LED blink onward. The register-level examples in our Embedded C programming guide use them throughout. If you want to see what the compiler actually emits for a given expression, the assembly language guide shows how to read it.