用于比特计数的元程序

时间:2010-10-12 10:08:14

标签: c++ templates metaprogramming

我需要C ++中的位计数器实用程序,它能够计算数值常量值中最高位的数字,并将此数字表示为编译时常量。

只是为了使一切清晰 - 一组数值的最重要位数:

 255 => 8   (11111111b)
   7 => 3   (111b)
1024 => 11  (10000000000b)
  26 => 5   (11010b)

我是模板编程的新手,但我认为就是这样。

请提供一些代码示例,我们将不胜感激。

2 个答案:

答案 0 :(得分:12)

编辑:我完全误读了你想要的东西。

这是你想要的:

0中的有效位数为0。

x中的有效位数是x/2中的有效位数加1。

所以你得到:

template <unsigned int x>
struct SignificantBits {
    static const unsigned int n = SignificantBits<x/2>::n + 1;
};

template <>
struct SignificantBits<0> {
    static const unsigned int n = 0;
};

答案 1 :(得分:1)

这是我的实施;它不像@ sepp2k那样优雅,它遵循不同的方法,实际上计算位数并提供MSB的位置和有效位数。

#include <iostream>
#include <limits>

// Number: the number to be examined; Bit: parameter used internally to specify the bit to
// examine (the work starts from the leftmost bit)
template<unsigned int Number, unsigned int Bit=std::numeric_limits<unsigned int>::digits-1>
class BitCounter
{
public:
    // Most Significant Bit number; if it's the current, fine, otherwise
    // delegate the work to another template that will examine the next bit
    static const int MSB=(Number&(1<<Bit))?Bit:BitCounter<Number,Bit-1>::MSB;
    // Count of significant bits - actually, MSB+1
    static const int Count=MSB+1;
};

// Corner case: we reached the first bit
template<unsigned int Number>
class BitCounter<Number,0>
{
public:
    // If it's 1, the MSB is the bit 0 (the rightmost), while if it's 0 it's "one before";
    // this is somewhat arbitrary to make Count get 0 for 0 and 1 for 1, you may want to
    // change it just to 0
    static const int MSB=Number==0?-1:0;
    static const int Count=MSB+1;
};

int main()
{
    std::cout<<BitCounter<255>::Count<<" "
             <<BitCounter<7>::Count<<" "
             <<BitCounter<1024>::Count<<" "
             <<BitCounter<26>::Count<<" "
             <<BitCounter<1>::Count<<" "
             <<BitCounter<0>::Count<<std::endl;
    return 0;
}

示例输出:

matteo@teoubuntu:~/cpp$ g++ tpl_bitcount.cpp -Wall -Wextra -ansi -pedantic -O3 -o tpl_bitcount.x && ./tpl_bitcount.x 
8 3 11 5 1 0