Fastest way to enumerate through turned on bits of an integer

后端 未结 8 1290
暗喜
暗喜 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:46

    I imagine bit-shifting would be the fastest. Untested, but I think the following ought to be fast (as fast as IEnumerables are at least).

    IEnumerable GetExponents(Int32 value)
    {
        for(int i=0; i<32; i++)
        {
            if(value & 1)
                yield return i;
            value >>= 1;
        }
    }
    

    If you want it to be faster, you might consider returning a List instead.

提交回复
热议问题