ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 24

Bit Manipulation in C

Setting, clearing and testing single bits.

Hardware registers pack many switches into one byte. To change one bit without disturbing the rest, use bitwise operators: OR sets, AND with an inverted mask clears, XOR toggles, AND tests.

Shifting 1 left by n creates a mask for bit n. Wrapping these in small macros keeps code readable.

Always use unsigned types for bit work to avoid sign surprises.

EXAMPLE
#define BIT(n)       (1u << (n))
#define SET(r, n)    ((r) |=  BIT(n))
#define CLEAR(r, n)  ((r) &= ~BIT(n))
#define TOGGLE(r, n) ((r) ^=  BIT(n))
#define TEST(r, n)   (((r) & BIT(n)) != 0)