Boost logo

Boost :

From: Vesa Karvonen (vesa_karvonen_at_[hidden])
Date: 2003-01-19 17:08:33


Gennaro Prota:
>Can someone who was subscribed when the Integer library was approved
>explain me what were the reasons to choose the current implementation
>of static_log2 against e.g.

I can't help in that, but

> template <unsigned long n>
> struct log2 {
> BOOST_STATIC_CONSTANT(unsigned long,
> value = 1 + (log2<n/2>::value));
> };
>
> template <>
> struct log2<1> {
> BOOST_STATIC_CONSTANT(unsigned long, value = 0);
> };

the above algorithm is inefficient and should not be used. Consider the
following algorithm instead:

#include <iostream>
#include <climits>

template<unsigned long x,
         int n = sizeof(unsigned long) * CHAR_BIT / 2>
struct log2 {
private:
  enum {c = (1 << n) <= x};
public:
  enum {value = c*n + log2<(x>>(c*n)),(n/2)>::value};
};

template<>
struct log2<1,0> {enum {value = 0};};

int main() {
  std::cerr << log2<1>::value << '\n';
  std::cerr << log2<2>::value << '\n';
  std::cerr << log2<3>::value << '\n';
  std::cerr << log2<5>::value << '\n';
  std::cerr << log2<6>::value << '\n';
  std::cerr << log2<7>::value << '\n';
  std::cerr << log2<8>::value << '\n';
  std::cerr << log2<(1<<20)>::value << '\n';

  return 0;
}

Regards,
  Vesa Karvonen

_________________________________________________________________
The new MSN 8 is here: Try it free* for 2 months
http://join.msn.com/?page=dept/dialup


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk