EmbedwrightArticlesLesson guideFree lessonsThe course · $79

Bit tricks every firmware engineer should know

By Chinmay Gupta · Updated 2026-10-10
Short answer. 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:

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;
}
Real output
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

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

This topic is Lesson 2 of DSA for Firmware, and that lesson is free. “The Sparrow board” teaches it with interactive labs and C exercises with tests. Read the lesson guide · Open Lesson 2
Want the full path from “I know C” to “I can choose the right data structure under a RAM budget”?
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.
Start Lesson 1 freeSee the full course · $79

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.

Chinmay Gupta
Chinmay Gupta is a firmware engineer with more than eight years of experience writing and debugging embedded C. He builds Embedwright's DSA for Firmware course.