Bit tricks every firmware engineer should know
x & (x - 1) clears the lowest set bit, x & -x isolates it, and counting trailing zeros gives the index of the highest-priority pending flag. __builtin_ctz is a GCC/Clang extension, so keep a portable fallback.Bit manipulation is firmware's native language. Registers are bit fields, interrupt controllers expose pending masks, and schedulers use bitmaps for ready queues. A handful of identities cover most of it.
The four identities
For an unsigned value x:
x & (x - 1)clears the lowest set bit. Applying it repeatedly counts the set bits (Kernighan's method).x & -xisolates the lowest set bit. For unsigned types the negation is well defined (modulo arithmetic).x != 0 && (x & (x - 1)) == 0tests thatxis a power of two.- The index of the lowest set bit is "count trailing zeros" (ctz).
Iterating over set bits
A pending-interrupt mask or a ready-task bitmap is walked one set bit at a time. Cost is proportional to the number of set bits, not the width of the register:
#include <stdint.h>
#include <stdio.h>
static unsigned popcount_kernighan(uint32_t x)
{
unsigned n = 0;
while (x) { x &= x - 1u; n++; }
return n;
}
static int is_pow2(uint32_t x) { return x != 0u && (x & (x - 1u)) == 0u; }
/* portable ctz via de Bruijn multiplication; x must be non-zero */
static unsigned ctz_portable(uint32_t x)
{
static const uint8_t table[32] = {
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 };
return table[((x & (0u - x)) * 0x077CB531u) >> 27];
}
int main(void)
{
uint32_t pending = 0x80010420u; /* bits 5, 10, 16, 31 */
printf("pending=0x%08X popcount=%u\n", (unsigned)pending, popcount_kernighan(pending));
for (uint32_t m = pending; m; m &= m - 1u) {
printf(" service IRQ %u\n", ctz_portable(m));
}
printf("is_pow2: 64 -> %d, 96 -> %d, 0 -> %d\n", is_pow2(64), is_pow2(96), is_pow2(0));
printf("lowest set bit of 0x%X is 0x%X\n", 0x2C0u, (unsigned)(0x2C0u & (0u - 0x2C0u)));
/* the fallback must agree with the compiler builtin for every non-zero input we try */
unsigned bad = 0;
for (unsigned i = 0; i < 32; i++) {
uint32_t v = 1u << i;
if (ctz_portable(v) != i || (unsigned)__builtin_ctz(v) != i) bad++;
}
uint32_t seed = 12345u;
for (unsigned i = 0; i < 100000; i++) {
seed = seed * 1664525u + 1013904223u;
if (seed && ctz_portable(seed) != (unsigned)__builtin_ctz(seed)) bad++;
if (popcount_kernighan(seed) != (unsigned)__builtin_popcount(seed)) bad++;
}
printf("fallbacks vs builtins: %s\n", bad ? "MISMATCH" : "all agree");
return bad ? 1 : 0;
}
pending=0x80010420 popcount=4 service IRQ 5 service IRQ 10 service IRQ 16 service IRQ 31 is_pow2: 64 -> 1, 96 -> 0, 0 -> 0 lowest set bit of 0x2C0 is 0x40 fallbacks vs builtins: all agree
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
(The test uses __builtin_ctz and __builtin_popcount as references, which is fine on GCC and Clang.)
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
Portability: what is standard and what is not
x & (x - 1),x & -xand shifts of unsigned values are plain ISO C.__builtin_ctz,__builtin_clzand__builtin_popcountare compiler extensions of GCC and Clang (other toolchains have their own intrinsics). Their result is undefined for an input of 0, so test for zero first.- C23 adds standard bit utilities in
<stdbit.h>(such asstdc_trailing_zeros), but your embedded toolchain may not support them yet. - Shifting by an amount greater than or equal to the type width is undefined behavior, so
1u << 32is a bug on a 32-bitunsigned.
What it costs on Cortex-M
Cortex-M3 and M4 have a CLZ instruction and a bit-reverse RBIT, so ctz compiles to two instructions. Cortex-M0 and M0+ have neither, so the compiler calls a library routine or you use a table such as the de Bruijn one above. The small table costs 32 bytes of flash and a few cycles; check your own map file before assuming either is "free".
Where it shows up
- Finding the highest-priority ready task in an RTOS bitmap scheduler.
- Walking a pending-interrupt or event-flag mask.
- Checking that a buffer size is a power of two, as in the ring buffer.
- Normalizing values for fixed-point math.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.