vimwiki

Bit hacks

Set a given bit to 1

// Set the nth bit to 1
x = (1 << n) | x

Clear a given bit (set it to 0)

// Set the nth bit to 0
x = ~(1 << n) & x

Toggle a bit

// toggle the nth bit
x = (1 << n) ^ x

Replace trailing 0 by 1

x = (x-1) | x

Convert positive to negative representation

x = (~x) + 1
// ex : 0010 -> 1110 = 2 -> -2

Extract least significant 1 bit

Take advantage of the property that the negative and positive representation of a number in bits only share the least significant 1 bit. For example 2 and -2, 0010 and 1110 share only the right most 1 is shared.

x &= -x

Remove the least significant 1 bit

x &= (x-1)