使用TMP表示值所需的计算位数
Calc number of bits needed to represent a value using TMP
我想使用模板元编程来计算我需要表示给定数字的最小位数。我以前从未使用过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;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 使用Qt C++计算类似Git的SHA1哈希
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 如何计算数据类型的范围,例如int
- 类似枚举的计算常量
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 计算缩放多边形的比例,得到给定的多边形面积
- 在C++中如何在没有pow的情况下进行基础计算
- 计算平均值,不包括上次得分
- 使用TMP表示值所需的计算位数