用于比特计数的元程序

Key*_*lug 5 c++ templates metaprogramming

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

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

 255 => 8   (11111111b)
   7 => 3   (111b)
1024 => 11  (10000000000b)
  26 => 5   (11010b)
Run Code Online (Sandbox Code Playgroud)

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

请提供一些代码示例,任何帮助将不胜感激.

sep*_*p2k 12

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

这是你想要的:

0中的有效位数为0.

有效位数xx/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;
};
Run Code Online (Sandbox Code Playgroud)

  • 此模板给出了"1"位的数量,但不是存储该值所需的最小位数.为此,您必须将`(x%2)`替换为`1`. (2认同)