Set / Clear / Toggle / Check
The four single-bit primitives, all built from a shifted mask 1 << k: OR sets, AND-with-inverse clears, XOR toggles, and AND tests a bit.
- Category
- Bit Manipulation
- Time complexity
- O(1)
- Space complexity
- O(1)
Pseudocode
mask ← 1 << k set: n |= mask clear: n &= ~mask toggle: n ^= mask check: (n >> k) & 1
Reference implementation
mask = 1 << k
n |= mask # set bit k
n &= ~mask # clear bit k
n ^= mask # toggle bit k
(n >> k) & 1 # check bit k
Open the interactive Set / Clear / Toggle / Check visualisation →