gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:03:38 31 4
gpt4 key购买 nike

我想使用模板元编程来计算表示给定数字所需的最少位数。我以前从未使用过 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("%i\n", bits<5000>::value);
return 0;
}

关于c++ - 使用 TMP 计算表示值所需的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24939771/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com