Bits, masks and hardware registers in C

c · folio

In one line: A register is a fixed address reached through a volatile uint32_t *; a field is a position + width — read it shift, then mask, write it clear, then OR, in unsigned arithmetic with shift counts below the width. r |= m is a load, an OR and a store: SET/CLR registers, bit-band aliases and write-1-to-clear flags exist so that one bit changes in one store.

Download PDF Print view LaTeX source

Bits, masks and hardware registers in C — figure 1

Six idioms

set nr |= 1u << nOR forces a 1
clear nr &= ~(1u << n)AND with a hole
toggle nr ̂= 1u << nXOR flips
test n(r >> n) & 1u0/1; !!(r & m) too
get field(r & Msk) >> PosMsk = shifted mask
put fieldr = (r & ~Msk) | ((v << Pos) & Msk)clear, OR; the last & Msk stops a too-big v

Put DIV = 0x15 into 0x002A3080: r & ~0x00FF0000 = 0x00003080; (0x15 << 16) & Msk = 0x00150000; OR → 0x00153080.

CMSIS (Arm)ESP-IDF soc/Linux
whereX_PosX_Sinside the mask
maskX_Msk (shifted)X_V plain, X_M shiftedGENMASK(h,l), BIT(n)
put_VAL2FLD(X,v)REG_SET_FIELD(r,X,v)FIELD_PREP(m,v)
get_FLD2VAL(X,r)REG_GET_FIELD(r,X)FIELD_GET(m,r)

FIELD_PREP rejects a non-constant mask, or a constant value too wide for it, at compile time.

Precedence — where bit tests break

Bits, masks and hardware registers in C — figure 2

Shifts — C23 6.5.8

Operands promoted; result type = the promoted left one; a count <0 or ≥ its width is UB for every type. C23’s mandatory two’s complement (6.2.6.2) changed none of it.

32-bit intresult
1u << 310x80000000; unsigned << wraps mod 2N
1 << 31UB: 231 is not an int value (GCC defines it as an extension; -fsanitize=shift still reports it)
-1 << 1UB: negative left operand
-8 >> 1implementation-defined; GCC sign-extends → -4
x << 32, x >> 32UB for uint32_t x: (1u << w) - 1 fails at w = 32; ~0u >> (32 - w) works for w 1..32
uint64_t m = 1 << 40;UB: still an int shift — 1ULL << 40
(uint8_t)0x80 << 24promoted to int, 231 → UB; cast to uint32_t first

Constants, widths, printing

  • Hex, octal, binary constants try int, unsigned, long, …: 0x80000000 is unsigned int; decimal 2147483648 is a (long) long.
  • C23: 0b1011'0100 (binary + ' separator); printf("%#b") → 0b10110100 (glibc ≥ 2.35); %w32x prints a uint32_t; UINT32_WIDTH = 32.
  • uintN_t is optional (defined when such a type exists); uint_leastN_t is required. UINT8_C(1) has the promoted type, int.
  • uint32_t may be unsigned long: ESP-IDF ≥ 5.0 (GCC 11) on Xtensa and RISC-V — "%u" warns, print with PRIx32.
  • Promotion: uint8_t x = 0xFF; ~x is the int -256, never 0 — write (uint8_t)~x. C23 unsigned _BitInt(N) is not promoted: ~ stays N bits (GCC 14+: x86, AArch64).

The lowest set bit

Bits, masks and hardware registers in C — figure 3
  • Loop x &= x - 1 to 0 = popcount in O(set bits) (Wegner 1960; K&R ex. 2-9). One bit set: x && !(x & (x - 1)) — forget x && and 0 passes.
  • a = 2k, unsigned h: h & (a - 1) = h % a; align up: (x + a - 1) & ~(a - 1).
  • Sign-extend a w-bit field (w ≤31): m = 1u << (w - 1), (int32_t)(x ̂ m) - (int32_t)m — no implementation-defined step.
  • Rotate, defined for n 0..31: (x << n) | (x >> (-n & 31)) (x >> (32 - n): UB at 0). GCC 15: __builtin_stdc_rotate_left.

<stdbit.h> (C23 7.18) vs the builtins

needC23GCC / Clangat 0
count 1sstdc_count_ones__builtin_popcount0
trailing 0sstdc_trailing_zeros__builtin_ctz32 · UB
leading 0sstdc_leading_zeros__builtin_clz32 · UB
ffs: index+1stdc_first_trailing_one__builtin_ffs0 · 0
one bit set?stdc_has_single_bitx && !(x&(x-1))false
bits neededstdc_bit_width32 - clz0 · UB
power of 2stdc_bit_floor / _ceil0 / 1

Suffixes _uc…_ull + type-generic (unsigned only); bit_ceil → 0 if 2k does not fit. Shipped by the C library (glibc 2.39, Jan 2024); GCC 14: __builtin_stdc_*, __builtin_clzg(x, 32) (2nd arg = result for 0). Byte order: __STDC_ENDIAN_NATIVE__.

Register access

#define REG32(a) (*(volatile uint32_t *)(a))
#define CTRL     REG32(PERIPH_BASE + 0x10u)  // illustrative
#define DIV_Pos  16u
#define DIV_Msk  (0xFFu << DIV_Pos)
uint32_t div = (CTRL & DIV_Msk) >> DIV_Pos;      // 1 load
CTRL = (CTRL & ~DIV_Msk) | ((v << DIV_Pos) & DIV_Msk);
STATUS = DONE;                       // W1C: write only that 1

volatile: each access in the source happens; what counts as one is implementation-defined (6.7.4.1). Read-only register: const volatile. No atomicity.

One bit, one store

Bits, masks and hardware registers in C — figure 4
  • ESP32 GPIO_OUT_W1TS / _W1TC (offset 0x08 / 0x0C) set / clear the 1-bits. ESP-IDF’s REG_SET_BIT, REG_SET_FIELD are plain C read-modify-writes.
  • STM32 GPIOx_BSRR: bits 0–15 set, 16–31 reset ODR — “no risk of an IRQ occurring between the read and the modify access”; both: set wins.
  • Bit-band (Cortex-M3/M4 option; not M0/M0+, ARMv8-M): alias = base + byte_offset×32 + bit×4; 1 MB of SRAM 0x2000_0000 → 0x2200_0000, of peripherals 0x4000_0000 → 0x4200_0000; 0x2200001C = bit 7 of 0x20000000. Bit 0 of the written word is the bit.

Status flags — how a bit is cleared

Bits, masks and hardware registers in C — figure 5

kindclears bywrite
rc_w1writing 1 (W1C): EXTI_PR, ESP32 STATUS_W1TCREG = F; REG |= F writes back every pending 1 and clears flags never handled
rc_w0writing 0: STM32 TIMx_SRSR = ~F; SR &= ~F zeroes flags raised between its load and store
rc_rbeing readany read is a side effect

C bit-fields vs hardware

Unit, order in it, straddling and a plain int field’s sign are implementation-defined (GCC: the ABI decides; int fields signed); no & of a field; :0 closes the unit. GCC: volatile bit-fields “may be implicitly read when written to, or when adjacent bit-fields are accessed” — “unwise” for hardware; -fstrict-volatile-bitfields (default: the ABI’s) forces one access of the declared width. ESP-IDF’s soc/*_struct.h uses them anyway.

Remember

OR sets, AND-NOT clears, XOR flips, shift-then-mask reads; one bit, one store.

Report a problem ·Discuss this folio