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

前端 未结 6 2374
说谎
说谎 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 21:06

    Here's the code using arithmetic shift + xor and Kernighan's method for bit counting:

    int count_transitions(int x)
    {
        assert((-1 >> 1) < 0); // check for arithmetic shift
        int count = 0;
        for(x ^= (x >> 1); x; x &= x - 1)
            ++count;
        return count;
    }
    

提交回复
热议问题