Compile-Time Log2

July 4, 2009 at 11:13 am 3 comments

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

Extremely concise guide to hotel guides The Return of the Comeback II

3 Comments Add your own

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed

Recent Posts


%d bloggers like this: