By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,413 Members | 1,023 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,413 IT Pros & Developers. It's quick & easy.

Log-base-2 function as compile-time constant

P: n/a

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.l...e4a60b0?hl=en&
Next time there's a rainy day, I might sit down with a pen and paper and
try to figure it out.
--

Frederick Gotham
Jul 1 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Frederick Gotham wrote:
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.l...e4a60b0?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

Jul 2 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.