Skip to content

Instantly share code, notes, and snippets.

@bazhenovc
Created January 16, 2018 00:12
Show Gist options
  • Save bazhenovc/846b6fbb4b7529dd22647763c2ad5f68 to your computer and use it in GitHub Desktop.
Save bazhenovc/846b6fbb4b7529dd22647763c2ad5f68 to your computer and use it in GitHub Desktop.
template <unsigned x> struct PopCount
{
enum {
a = x - ((x >> 1) & 0x55555555),
b = (((a >> 2) & 0x33333333) + (a & 0x33333333)),
c = (((b >> 4) + b) & 0x0f0f0f0f),
d = c + (c >> 8),
e = d + (d >> 16),
result = e & 0x0000003f
};
};
template <unsigned x> struct Log2
{
enum {
a = x | (x >> 1),
b = a | (a >> 2),
c = b | (b >> 4),
d = c | (c >> 8),
e = d | (d >> 16),
f = e >> 1,
result = PopCount<f>::result
};
};
template <unsigned min, unsigned max> struct BitCount
{
enum {
result = (min == max) ? 0 : (Log2<uint32_t(max - min)>::result + 1)
}
};
// example usage
U32 bitCount = BitCount<128, 512>::result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment