使用TMP表示值所需的计算位数

Calc number of bits needed to represent a value using TMP

本文关键字:计算 TMP 表示 使用      更新时间:2023-10-16

我想使用模板元编程来计算我需要表示给定数字的最小位数。我以前从未使用过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 ++;

这应该是你想要的

#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("%in", bits<5000>::value);
    return 0;
}