Calc使用TMP表示值所需的位数

时间:2014-07-24 16:59:47

标签: c++ templates template-meta-programming

我想使用模板元编程来计算表示给定数字所需的最小位数。我之前从未使用过TMP,所以可能是完全可笑的。

struct ValueHolder
{
   typedef float value;
};

template<struct ValueHolder>
struct logB2
{
   enum { result = (((*(int*)&ValueHolder.value & 0x7f800000) >> 23) - 127) };
};

template <struct logB2 n>
struct bits2use {

    enum { return = !((n::return > 0) && !(n::return & (n::return-1))) ? n++ : n };
};

#ifndef NUM 
#define NUM 18 
#endif

int main()
{
   std::cout << bits2use<NUM>::return << '\n';
   return 0;
}

以下是我所知道的运行时代码的工作原理:

int ch_bits;                    //how many bits needed to send the channel
float xf = CHN_CNT;             //need a float for log2 calc
int x = CHN_CNT;

//Calculate how many bits you need for a given integer, i.e. for a 64 channels you need
//6 bits to represent 0-63 unsigned.
ch_bits = ((*(int*)&xf & 0x7f800000) >> 23) - 127;  //log_2
if( !((x > 0) && !(x & (x-1))) )                    //true if x is not a power of 2
    ch_bits ++;

1 个答案:

答案 0 :(得分:1)

这应该做你正在寻找的事情

#include <stdio.h>

template<int N> struct bits;
template<> struct bits<1> { enum { value=1 }; };
template<int N> struct bits { enum { value = 1 + bits<(N>>1)>::value }; };

int main() {
    printf("%i\n", bits<5000>::value);
    return 0;
}