Fastest way to enumerate through turned on bits of an integer

后端 未结 8 1196
暗喜
暗喜 2021-02-06 08:22

What\'s the fastest way to enumerate through an integer and return the exponent of each bit that is turned on? Have seen an example using << and another u

8条回答
  •  不思量自难忘°
    2021-02-06 08:45

    Fastest given what distribution for the input? If typically only one bit is set, then this could be faster than looping through looking for set bits.

    Taking from the accepted answer for finding the position of the least significant bit, which took from Bit Twiddling Hacks, this solutions loops, finding, clearing and returning the position of each consecutive least-significant-bit.

       static int[] MulDeBruijnBitPos = new int[32] 
        {
          0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 
          31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
        };
    
        static IEnumerable GetExponents(UInt32 v)
        {
            UInt32 m;
    
            while( v != 0 ) {
              m = (v & (UInt32) (-v));
              yield return MulDeBruijnBitPos[((UInt32) (m * 0x077CB531U)) >> 27];
              v ^= m;
            }
        }
    

    It only loops as many times as there are bits set.

提交回复
热议问题