Compile-Time Log2
July 4, 2009
While I was looking for a compile-time Log2 calculation for integer numbers, I couldn’t find anything simple and concise enough.
So I wrote something myself, putting all my trust in the good old compiler. This is what I came up with. It’s so simple that I cannot believe nobody came up with this before, but anyways, here it is :
//Description: a compile time truncated log2 for integer values
template< size_t ac_Val > struct CLog2
{
static const size_t result = CLog2< ac_Val / 2 >::result + 1 ;
};
template<> struct CLog2< 1 > { static const size_t result = 0 ; } ;
template<> struct CLog2< 0 > { } ; // undefined
Of course, the truncated Log2 is also the index of the highest set bit in an integer number.
Entry Filed under: Command Line. Tags: c++, code, compile-time, programming, templates.
3 Comments Add your own
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed
1.
qbziz | July 4, 2009 at 2:15 pm
Apparently I didn’t look hard enough : http://stackoverflow.com/questions/994593/will-floating-point-precision-errors-affect-this-code
Look for “Compile-time solution, anyone?”
2.
stijn | July 6, 2009 at 9:03 am
shouldn’t that be
template struct CLog2 { } ;
etc ?
3.
qbziz | July 6, 2009 at 9:09 am
lol. i know what you meant to say, but alas, you fell into the same trap i did with regard to html.
but still i fixed it