Quiz Entry - updated: 2026.07.10
How do you set, clear, and toggle a specific bit in C?
Set with OR (flags |= 1<<n), clear with AND-NOT (flags &= ~(1<<n)), and toggle with XOR (flags ^= 1<<n).
#define BIT(n) (1 << (n))
// SET bit n (force to 1)
flags |= BIT(n);
flags |= (1 << n);
// CLEAR bit n (force to 0)
flags &= ~BIT(n);
flags &= ~(1 << n);
// TOGGLE bit n (flip 0↔1)
flags ^= BIT(n);
flags ^= (1 << n);
Example with bit 2:
// 00000001
unsigned char flags = 0x01;
// SET: 00000101 (0x05)
flags |= (1 << 2);
// CLEAR: 00000001 (0x01)
flags &= ~(1 << 2);
// TOGGLE: 00000101 (0x05)
flags ^= (1 << 2);
// TOGGLE: 00000001 (0x01)
flags ^= (1 << 2);
Why these work:
x | 1 = 1(OR with 1 always gives 1)x & 0 = 0(AND with 0 always gives 0)x ^ 1 = ~x(XOR with 1 flips the bit)