basics · beginner · ~15 min
Flip a single bit with XOR.
Implement:
unsigned toggle_bit(unsigned x, int i);
Return x with bit i flipped. i is in 0..31.
x and a bit index i.
x with bit i inverted.
i in 0..31.
#include <stddef.h>
/* Return x with bit i flipped. i in 0..31. */
unsigned toggle_bit(unsigned x,int i){ (void)i; return x; }
Using | (set) or & ~ (clear) instead of ^ (flip).
Toggling twice restores the original value.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.