Skip to content

Instantly share code, notes, and snippets.

@isilence
Last active July 7, 2019 12:05
Show Gist options
  • Save isilence/c3395728159a8c602fc6e71ea03318bb to your computer and use it in GitHub Desktop.
Save isilence/c3395728159a8c602fc6e71ea03318bb to your computer and use it in GitHub Desktop.
Fast most significant bit
inline unsigned long msb_intrin(unsigned long x)
{
const int zs = __builtin_clzl(x);
return 1ul << (sizeof(x) * CHAR_BIT - zs - 1);
}
inline unsigned long msb_fast(unsigned long x)
{
int bit_size = sizeof(x) * CHAR_BIT;
#pragma unroll
for (int j = 0; (1 << j) < bit_size; ++j)
x |= x >> (1 << j);
return x - (x >> 1);
}
inline unsigned long msb_bitset(unsigned long x)
{
unsigned long t;
do {
t = x;
x &= x - 1ul;
} while (x != 0ul);
return t;
}
msb_intrin: O(1) 0.001 ms
msb_fast: O(log(log(num))) 305.606 ms
msb_avg: O(# of set bits) 1202.82 ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment