Skip to content

Instantly share code, notes, and snippets.

@kusma
Last active January 31, 2017 13:47
Show Gist options
  • Save kusma/47930 to your computer and use it in GitHub Desktop.
Save kusma/47930 to your computer and use it in GitHub Desktop.
compile-time calculate the magnitude (the number of bits needed to store a number) of a given number
template <unsigned int n, unsigned int bit = 31>
struct mag
{
enum {
lval = (n & (1UL << bit)) != 0 ? bit : 0,
rval = mag<n, bit - 1>::value,
value = lval > rval ? lval : rval // max
};
};
template <unsigned int n>
struct mag<n, 0>
{
enum { value = (n & 1) != 0 ? 1 : 0 };
};
int main(int argc, char *argv[])
{
printf("%d\n", mag<63>::value);
printf("%d\n", mag<64>::value);
printf("%d\n", mag<256>::value);
printf("%d\n", mag<0>::value);
printf("%d\n", mag<1 << 16>::value);
printf("%d\n", mag<(1 << 16) - 1>::value);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment