Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Embedded C

Bit Manipulation for Registers

Master set, clear, toggle and test of register bits in C with masks and shifts, multi-bit fields, read-modify-write hazards and reusable macros, all runnable.

Almost everything you do to hardware in firmware comes down to changing individual bits in registers. One bit enables a peripheral clock, another selects a pin as output, a group of three bits selects a baud rate divisor, and one status bit tells you a byte has arrived. Because a register is just a 32-bit (or 8- or 16-bit) integer, you manipulate those bits with C's bitwise operators: &, |, ^, ~, << and >>.

This lesson teaches the five operations you will type hundreds of times: set, clear, toggle, test and write a multi-bit field. You also learn why order matters, what a read-modify-write is, and how to build macros so your code reads like the datasheet.

The operators in 30 seconds

Operator Meaning Example (8-bit)
a & b AND: 1 only where both are 1 0b1100 & 0b1010 = 0b1000
a | b OR: 1 where either is 1 0b1100 | 0b1010 = 0b1110
a ^ b XOR: 1 where they differ 0b1100 ^ 0b1010 = 0b0110
~a NOT: flip every bit ~0b00001100 = 0b11110011
a << n shift left, fill with 0 0b0001 << 3 = 0b1000
a >> n shift right 0b1000 >> 3 = 0b0001

Do not confuse & and | (bitwise) with && and || (logical). if (flags & 0x04) tests a bit; if (flags && 0x04) just checks that both are non-zero.

The five patterns

Let REG be a register and n a bit number counted from 0 at the least significant end. The mask for bit n is (1u << n).

C
REG |=  (1u << n);     // SET bit n          -> 1
REG &= ~(1u << n);     // CLEAR bit n        -> 0
REG ^=  (1u << n);     // TOGGLE bit n       -> flips
if (REG & (1u << n)) { /* bit n is 1 */ }    // TEST bit n
REG = (REG & ~MASK) | (value << SHIFT);      // WRITE a multi-bit field

Why they work:

  • Set: OR with a 1 forces a 1; OR with 0 leaves a bit alone.
  • Clear: ~mask has a 0 only at the target bit; AND with it zeroes that bit and keeps the rest.
  • Toggle: XOR with 1 flips; with 0 does nothing.
  • Test: AND with the mask leaves only that bit; the result is non-zero if the bit is set.
C Set, clear, toggle and test, with binary output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Multi-bit fields

Many register fields are wider than one bit. Suppose a clock register has a 3-bit prescaler in bits 4-6 (0b111 << 4). To write the value 5 into that field without disturbing other bits: first clear the field with its mask, then OR in the new value shifted into place.

C
#define PRESC_SHIFT 4u
#define PRESC_MASK  (0x7u << PRESC_SHIFT)

reg = (reg & ~PRESC_MASK) | ((5u << PRESC_SHIFT) & PRESC_MASK);

The final & PRESC_MASK protects the neighbors if the value is too big. To read the field back: (reg & PRESC_MASK) >> PRESC_SHIFT.

C Writing and reading a multi-bit field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Read-modify-write and why it matters

REG |= (1u << 3) is three steps: read the register, modify the value, write it back. If an interrupt changes another bit of the same register between your read and write, that change is lost, because you write back the old value for the other bits. Likewise, some registers have write-1-to-clear flag bits: reading and writing back a status register would clear flags you never meant to touch.

Hardware designers help in several ways:

  • Set/clear registers: separate registers BSRR (STM32) or SET/CLR (RP2040, nRF) where writing a 1 sets or clears just that bit atomically. No read needed.
  • Bit-banding on Cortex-M3/M4: each bit of a region has its own word address; a single store changes one bit atomically.
  • Atomic instructions and disabling interrupts around a critical section.

A rule worth remembering: when a register has a write-only set/clear pair, use it. Chapter 5 returns to protecting shared data from interrupts.

Useful idioms

Task Code
Is the value a power of two? x && !(x & (x - 1))
Clear the lowest set bit x & (x - 1)
Isolate the lowest set bit x & -x (for unsigned: x & (~x + 1))
Count set bits loop with x &= x - 1, or __builtin_popcount(x)
Swap two variables without a temp a ^= b; b ^= a; a ^= b; (a party trick: use a temp)
Extract bits n..m (x >> n) & ((1u << (m - n + 1)) - 1)
Reverse the bits of a byte table lookup or a loop
Rotate left by n (8 bit) (x << n) | (x >> (8 - n))
Parity XOR-fold: x ^= x >> 4; x ^= x >> 2; x ^= x >> 1; x & 1
C Bit tricks used in drivers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Macros that read like datasheets

Instead of scattering (1u << 5) through your code, name the bits:

C
#define BIT(n)          (1u << (n))
#define SET_BIT(r, n)   ((r) |=  BIT(n))
#define CLR_BIT(r, n)   ((r) &= ~BIT(n))
#define TGL_BIT(r, n)   ((r) ^=  BIT(n))
#define TEST_BIT(r, n)  (((r) >> (n)) & 1u)

#define UART_CR_ENABLE  BIT(0)
#define UART_CR_TXEN    BIT(3)
#define UART_CR_RXEN    BIT(4)

Then UART->CR |= UART_CR_ENABLE | UART_CR_TXEN; states intent. Always parenthesize macro arguments, and avoid macro arguments with side effects (SET_BIT(r, i++) would evaluate i++ more than once). Macros, Inline Functions and Compile-Time Checks discusses safer alternatives.

Common mistakes

  1. Forgetting u on the mask. 1 << 31 is signed overflow. Write 1u << 31.
  2. Using = instead of |=. PORT = (1u << 3) changes every bit, not only bit 3.
  3. Mixing up bit number and mask. REG |= 5 sets bits 0 and 2; REG |= (1u << 5) sets bit 5.
  4. Forgetting parentheses. x & 1 << n parses as x & (1 << n) but x & y == z parses as x & (y == z). Parenthesize.
  5. Shifting by a number greater than or equal to the width. Undefined behavior.
  6. Testing with == 1. (reg & (1u << 3)) == 1 is false when the bit is set (it equals 8). Test != 0.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement clears bit 5 of REG and leaves the other bits unchanged?

    ~(1u << 5) has a 0 only at bit 5, so ANDing keeps all other bits and clears bit 5.
  2. 2. Why is (reg & (1u << 3)) == 1 usually a bug?

    AND with the mask keeps the bit in its original position, so the value is 8, not 1. Compare with != 0.
  3. 3. What is the danger of read-modify-write on a shared register?

    The write-back overwrites changes made by an interrupt or another hardware event. Use atomic set/clear registers or protect the sequence.
  4. 4. To write the value v into a 3-bit field at bits 4-6, you should:

    Clearing first removes old field bits; masking the new value protects neighbors from an oversized v.

Summary

  • Set with |=, clear with &= ~mask, toggle with ^=, test with &; always use 1u << n masks.
  • To write a multi-bit field: clear it with its mask, then OR in the shifted, masked value.
  • Read-modify-write is not atomic; prefer hardware set/clear registers or short critical sections.
  • Name bits and fields with macros so code reads like the datasheet.
  • Parenthesize, use unsigned constants and test with != 0.

Next: volatile, const and static