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: , , , , .

3 Comments Add your own

Leave a Comment

Required

Required, hidden

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


Recent Posts

Categories