Last active
January 31, 2017 13:47
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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