</>EmbeddedInterview
← All problems · Bit Manipulation

Set, Clear, Toggle and Test a Bit

Easy

Write four functions that operate on a 32-bit register value: bit_set, bit_clear, bit_toggle and bit_test. Each takes the value and a bit position n (0–31). The first three return the new value; bit_test returns true if bit n is set.

This is the most common opening question in firmware interviews. Write it without hesitation and explain why you use 1u.

Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Build a mask with a single 1 at position n by shifting 1u. OR sets, AND with the inverted mask clears, XOR toggles.

#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>

uint32_t bit_set(uint32_t v, unsigned n)    { return v | (1u << n); }
uint32_t bit_clear(uint32_t v, unsigned n)  { return v & ~(1u << n); }
uint32_t bit_toggle(uint32_t v, unsigned n) { return v ^ (1u << n); }
bool     bit_test(uint32_t v, unsigned n)   { return (v >> n) & 1u; }

Using 1u makes the shift unsigned. With a plain 1, 1 << 31 shifts into the sign bit of a signed int, which is undefined behaviour before C23. Shifting by 32 or more is undefined for any type, so production code often adds n &= 31 or an assertion.

Follow-ups: How would you do this on a real register shared with an ISR? (Critical section, or atomic set/reset registers like STM32 BSRR.) What about a multi-bit field? See Extract and Insert a Register Field.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    CHECK(bit_set(0, 0) == 1u);
    CHECK(bit_set(0, 31) == 0x80000000u);
    CHECK(bit_clear(0xFFu, 3) == 0xF7u);
    CHECK(bit_toggle(0x10u, 4) == 0u);
    CHECK(bit_toggle(0u, 7) == 0x80u);
    CHECK(bit_test(0x8u, 3));
    CHECK(!bit_test(0x8u, 2));
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}