Log-base-2 function as compile-time constant

  • Thread starter Frederick Gotham
  • Start date
F

Frederick Gotham

I've mentioned his name a few times here lately, but over on comp.lang.c,
Hallvard B Furuseth has come up with a Log-base-2 function that serves as a
compile-time constant.

I'm not going to pretend to even begin to understand how it works, but if
anyone's interested, here's a link to the post:

http://groups.google.ie/group/comp.lang.c/msg/706324f25e4a60b0?hl=en&


Next time there's a rainy day, I might sit down with a pen and paper and
try to figure it out.
 
L

Luke Meyers

Frederick said:
I've mentioned his name a few times here lately, but over on comp.lang.c,
Hallvard B Furuseth has come up with a Log-base-2 function that serves as a
compile-time constant.

I'm not going to pretend to even begin to understand how it works, but if
anyone's interested, here's a link to the post:

http://groups.google.ie/group/comp.lang.c/msg/706324f25e4a60b0?hl=en&

Next time there's a rainy day, I might sit down with a pen and paper and
try to figure it out.

My goodness, how convoluted. Luckily in C++ we have no need for such
macro-heavy measures when we want compile-time constants:

#include "boost/static_assert.hpp"

template <size_t N, size_t base=2>
struct log_
{
enum { value = 1 + log_<N/base, base>::value };
};

template <size_t base>
struct log_<1, base>
{
enum { value = 0 };
};

template <size_t base>
struct log_<0, base>
{
enum { value = 0 };
};

int main()
{
BOOST_STATIC_ASSERT(log_<0>::value == 0);
BOOST_STATIC_ASSERT(log_<1>::value == 0);
BOOST_STATIC_ASSERT(log_<2>::value == 1);
BOOST_STATIC_ASSERT(log_<3>::value == 1);
BOOST_STATIC_ASSERT(log_<4>::value == 2);
BOOST_STATIC_ASSERT(log_<5>::value == 2);
BOOST_STATIC_ASSERT(log_<8>::value == 3);
BOOST_STATIC_ASSERT(log_<16>::value == 4);
BOOST_STATIC_ASSERT(log_<246>::value == 7);

return 0;
}

Experiment to your heart's content with other bases, negative numbers,
limits, etc.

Cheers,
Luke
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top