Collection of bit mask operation


Standard operations

Set the ithi^{th} bit

mask |= 1 << i

Unset the ithi^{th} bit

mask &= ~(1 << i)

Toggle the ithi^{th} bit

mask ^= 1 << i

Check if ithi^{th} bit is set

mask & (1 << i)

Get the lowest bit (least significant bit)

x & -x

C++ specific functions

Count bit 1s

__builtin_popcount(n)
// pop means population

Count trailing zeros

__builtin_ctz(n)
// ctz means count trailing zero

Count leading zeroes

__builtin_clz(n)
// clz means count leading zero

Check if n is power of 2

__builtin_popcount(n) == 1
Made with love using Svelte, Three.js