Skip to content

Instantly share code, notes, and snippets.

@bazhenovc
Created January 13, 2018 01:37
Show Gist options
  • Save bazhenovc/f6241edc38efe3687e4a984d69795670 to your computer and use it in GitHub Desktop.
Save bazhenovc/f6241edc38efe3687e4a984d69795670 to your computer and use it in GitHub Desktop.
template <typename T>
constexpr unsigned BitsRequired(T min, T max)
{
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
};
};
return (min == max) ? 0 : (Log2<uint32_t(max - min)>::result + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment