Skip to content

Instantly share code, notes, and snippets.

@B1Z0N
Created February 2, 2020 13:23
Show Gist options
  • Save B1Z0N/e494241b49089dc55027c5e7353040f2 to your computer and use it in GitHub Desktop.
Save B1Z0N/e494241b49089dc55027c5e7353040f2 to your computer and use it in GitHub Desktop.
The collection of useful bit operations for speed and sanity purposes
// Number of leading zeroes: builtin_clz(x)
// Number of trailing zeroes : builtin_ctz(x)
// Number of 1-bits: __builtin_popcount(x)
// The parity (even or odd) of the number of ones: __builtin_parity(x)
// a * 2^n
constexpr int multiplyByPowerOf2(int a, int n) {
return a << n;
}
// a / 2^n
constexpr int divideByPowerOf2(int a, int n) {
return a >> n;
}
// quickest way to swap to numbers
constexpr void xorswap(int& a, int& b) {
a ^= b;
b ^= a;
a ^= b;
}
// Highest power of 2 that divides a given number
constexpr int highestPowerof2(int n) {
return n & (~(n - 1));
}
constexpr bool isPowerOfTwo(int x)
{
// First x in the below expression is
// for the case when x is 0
return x && (!(x & (x - 1)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment