Bitwise Operations

When dealing with integer types only, bitwise operations are in most cases faster than plain math. Because those tricks are not realy "special" I put the most common ones on this page and you should have a more detailed look at the See Also section.

Multiplication By 2^x
A simple multiplication in the form of 2^x could be something like y * 2 or y * 4.

y *= 2^x y <<= x

Division By 2^x
A simple division in the form of 2^x could be something like y / 2 or y / 4.

y /= 2^x y >>= x

Modulo 2^x
A simple modulo in the form of 2^x could be something like y % 2 or y % 4.

y %= 2^x y &= 2^x - 1

Test If x Is Even
Testing if a a variable is even or odd has a lot of applications and can be done using bitwise operations.

isEven = 0 == (x % 2) isEven = 0 == (x & 1)