</>EmbeddedInterview

How do you set, clear, toggle and check the nth bit?

EasyBit Manipulation

Short answer: Build a mask with 1u << n, then use OR to set, AND with the inverted mask to clear, XOR to toggle and AND to test.

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

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

/* In-place versions, the style many people write first: */
void set_nth_bit(uint32_t *num, unsigned n)   { *num |=  (1u << n); }
void clear_nth_bit(uint32_t *num, unsigned n) { *num &= ~(1u << n); }

Why each works

  • OR with 1 forces a bit to 1; OR with 0 leaves it unchanged. The mask has a single 1, so only bit n changes.
  • ~(1u << n) is all ones except bit n. AND with 0 forces that bit to 0 and AND with 1 keeps the others.
  • XOR with 1 flips a bit; XOR with 0 keeps it.
  • x & (1u << n) is non-zero if bit n is set. It is not 1; it is 2ⁿ. If you need exactly 0 or 1, use (x >> n) & 1u or !!(x & (1u << n)).

Worked example: x = 0b1010, n = 2. Set gives 0b1110, clear gives 0b1010 (already clear), toggle gives 0b1110, test gives 0.

Common mistakes

  • Using int and 1 << 31: undefined behaviour. Use uint32_t and 1u.
  • Shifting by 32 or more: undefined for a 32-bit type. Check n < 32 or mask n &= 31.
  • Writing bit = number & (1 << n) and then comparing bit == 1. That is only true for n == 0.

Follow-up on real hardware: reg |= mask on a peripheral register is a read-modify-write. If an ISR changes the same register between the read and the write, the ISR's change is lost. Fixes: disable interrupts around it, use hardware set/clear registers (STM32 GPIOx->BSRR, NXP SET/CLR registers), or Cortex-M bit-banding.