Common Bit Tricks

Useful patterns to memorize.

Check if ii-th bit is set:

(n >> i) & 1
// or: n & (1 << i)

Set the ii-th bit:

n = n | (1 << i)

Clear the ii-th bit:

n = n & ~(1 << i)

Toggle the ii-th bit:

n = n ^ (1 << i)

Check if power of two:

n > 0 and (n & (n - 1)) == 0

Clear the lowest set bit:

n = n & (n - 1)

Isolate the lowest set bit:

lowBit = n & (-n)

These run in O(1)O(1) time.