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 &lt;&lt; k
n |= mask       # set bit k
n &amp;= ~mask      # clear bit k
n ^= mask       # toggle bit k
(n &gt;&gt; k) &amp; 1     # check bit k

Open the interactive Set / Clear / Toggle / Check visualisation →