Fastest way to count number of bit transitions in an unsigned int

前端 未结 6 2300
说谎
说谎 2021-02-09 20:31

I\'m looking for the fastest way of counting the number of bit transitions in an unsigned int.

If the int contains: 0b0000000000000000000000000000101

6条回答
  •  长发绾君心
    2021-02-09 20:54

    int numTransitions(int a)
    {
      int b = a >> 1; // sign-extending shift properly counts bits at the ends
      int c = a ^ b;  // xor marks bits that are not the same as their neighbors on the left
      return CountBits(c); // count number of set bits in c
    }
    

    For an efficient implementation of CountBits see http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel

提交回复
热议问题