计算比特和位反转的数量

时间:2011-03-28 08:30:01

标签: c++ c bit

  

可能重复:
  How many 1s in an n-bit integer?

您好

如何计算有多少位?

1100110 -> 4
101 -> 2

第二个问题:

如何反转位?

1100110 -> 0011001
101 -> 010

由于

9 个答案:

答案 0 :(得分:5)

如果您可以将您的位变为std::bitset,则可以使用flip方法进行反转,使用count方法对位进行计数。

答案 1 :(得分:4)

Henry S Warren Jr.的书 Hacker's Delight 包含许多有用的小宝石来计算这类东西 - 还有很多其他东西。每个做低级别的人都应该有一份副本:)

count-1s部分长8页!

其中一个是:

int pop(unsigned x)
{
    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0F0F0F0F;
    x = x + (x >> 8);
    x = x + (x >> 16);
    return x & 0x0000003F;
}

与已经提出的循环选项相比,潜在的关键优势是运行时不可变。如果它在硬实时中断服务程序中,这比“最快平均计算”时间重要得多。

这里还有一个关于位计数的长线程: How to count the number of set bits in a 32-bit integer?

答案 2 :(得分:3)

  1. 您可以在数字非零时循环,并在最后一位设置时递增计数器。或者,如果您正在使用英特尔架构,则可以在内联汇编中使用popcnt指令。

    int count_bit_set(unsigned int x) {
        int count = 0;
        while (x != 0) {
            count += (x & 1);
            x = x >> 1;
        }
        return count;
    }
    
  2. 您使用~运算符。

答案 3 :(得分:1)

答案 4 :(得分:1)

对于第一个问题,Fast Bit Counting有几种方法可以做到,最简单的是:

int bitcount (unsigned int n) {
   int count = 0;
   while (n) {
      count += n & 0x1u;
      n >>= 1;
   }
   return count;
}

对于第二个问题,请使用´~´ (bitwise negation) operator

答案 5 :(得分:1)

要计算一个数字中的设置位数,您可以使用hakmem并行计数,这是不使用预定义表进行并行计数的最快方法:

http://tekpool.wordpress.com/2006/09/25/bit-count-parallel-counting-mit-hakmem/

反转位非常简单:

i = ~i;

答案 6 :(得分:1)

有点琐碎(但更快)的解决方案是:

int setbitcount( unsigned int x )
{
    int result;
    for( result=0; x; x&=x-1, ++result )
        ;
    return result;
}

与sylvain的灵魂相比,此函数仅在循环中迭代设置位的数量。即:对于数字1100110,它将只进行4次迭代(与Sylvain算法中的32次相比)。

关键是表达式x& = x-1,它将清除最不重要的设置位。即:
1)1100110& 1100101 = 1100100
2)1100100& 1100011 = 1100000
3)110000& 1011111 = 1000000
4)1000000& 0111111 = 0

答案 7 :(得分:1)

你也可以通过XOR将它们反转一些数字。
例如 - 反转字节: INVERTED_BYTE = BYTE ^ 0xFF

答案 8 :(得分:0)

How to calculate how many ones in bits?

Hamming weight.

How to invert bits?

i = ~i;

相关问题