Thursday, December 8, 2016

Shift Operator, ilog2 and test power of 2

(1) shift left of 1 generate all powers of 2.
(2) ilog2 is template specialization.
(3) shift 1 by ilog2(n) will get back n for power of 2 only
(4) compiler say too complex when using recursion for non-template function is_power_of_2

#include "stdafx.h"
#include <iostream>

using namespace std;

template <size_t X>
struct ilog2
{
 enum {value=(1+ilog2<X/2>::value) };
};

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

template<size_t N>
bool is_pow_of_2()
{
 return ((size_t)1 << ilog2<N>::value == N);
};

int main() {
 
 cout << (1 << 3) << endl; // 8
 cout << (1 << 9) << endl; // 512=2 power 9
 
 cout << ((size_t)1 << ilog2<9>::value == 9) << endl;
 cout << ((size_t)1 << ilog2<512>::value == 512) << endl;
 
 cout << is_pow_of_2<9>() << endl;
 cout << is_pow_of_2<512>() << endl;
 return 0;
}



No comments:

Post a Comment