396 24.BitHacksforGames
Formula Operation / Effect Notes
x & (x - 1) Clear lowest 1 bit. If result is 0, then x is 2
n
.
x | (x + 1) Set lowest 0 bit.
x | (x - 1) Set all bits to right of lowest 1 bit.
x & (x + 1) Clear all bits to right of lowest 0 bit. If result is 0, then x is 21
n
.
x & -x Extract lowest 1 bit.
~x & (x + 1) Extract lowest 0 bit (as a 1 bit).
~x | (x - 1) Create mask for bits other than lowest 1 bit.
x | ~(x + 1) Create mask for bits other than lowest 0 bit.
x | -x Create mask for bits left of lowest 1 bit, inclusive.
x ^ -x Create mask for bits left of lowest 1 bit, exclusive.
~x | (x + 1) Create mask for bits left of lowest 0 bit, inclusive.
~x ^ (x + 1) Create mask for bits left of lowest 0 bit, exclusive. Also x ≡ (x + 1).
x ^ (x - 1) Create mask for bits right of lowest 1 bit, inclusive. 0 becomes 1
.
~x & (x - 1) Create mask for bits right of lowest 1 bit, exclusive. 0 becomes 1
.
x ^ (x + 1) Create mask for bits right of lowest 0 bit, inclusive. 1
remains 1
.
x & (~x - 1) Create mask for bits right of lowest 0 bit, exclusive. 1
remains 1
.
Table 24.4. Logic formulas and their effect on the binary representation of a signed integer.
References
[Anderson 2005] Sean Eron Anderson. “Bit Twiddling Hacks.” 2005. Available at http://
graphics.stanford.edu/~seander/bithacks.html.
[Ericson 2008] Christer Ericson. “Advanced Bit Manipulation-fu.” realtimecollision de-
tection.net - the blog, August 24, 2008. Available at http://realtimecollision detec-
tion.net/blog/?p=78.
[Hoxey et al. 1996] Steve Hoxey, Faraydon Karim, Bill Hay, and Hank Warren, eds. The
PowerPC Compiler Writer’s Guide. Palo Alto, CA: Warthman Associates, 1996.