Search topics...
C / C++ ConceptsBit Manipulationfoundational

How do you set, clear, and toggle a specific bit in a register?

0 upvotes
Practice with AISoon
c
#define BIT(n) (1U << (n))
reg |= BIT(3); // Set bit 3
reg &= ~BIT(3); // Clear bit 3
reg ^= BIT(3); // Toggle bit 3

Use |= to set (OR with the mask), &= ~ to clear (AND with the inverted mask), and ^= to toggle (XOR with the mask). Always use 1U (unsigned) rather than 1 to avoid undefined behavior when shifting into the sign bit. For multi-bit fields, use mask-and-shift: reg = (reg & ~(0x7 << 4)) | (value << 4); to write a 3-bit field at position 4.

Never use direct assignment (reg = BIT(3)) — this clears all other bits in the register.

Source: C / C++ Concepts Q&A