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

前端 未结 6 2309
说谎
说谎 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:56

    In C/C++ I would do the following:

    unsigned int Transitions(unsigned int value)
    {
        unsigned int result = 0;
    
        for (unsigned int markers = value ^ (value >> 1); markers; markers = markers >> 1)
        {
            if (markers & 0x01) result++;
        }
    
        return result;
    }
    

提交回复
热议问题