枚举最快的方式,通过开启一个整数位 [英] Fastest way to enumerate through turned on bits of an integer

查看:114
本文介绍了枚举最快的方式,通过开启一个整数位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是通过一个整数枚举并返回开启每个位的指数最快的方法是什么? <采用与LT见过一个例子;而另一个使用Math.Pow。想知道是否有其他任何的真快。

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 using Math.Pow. Wondering if there is anything else that's really fast.

感谢。

推荐答案

我想象位移将是最快的。未经检验的,但我觉得有以下应该是快(快IEnumerables至少)。

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<int> GetExponents(Int32 value)
{
    for(int i=0; i<32; i++)
    {
        if(value & 1)
            yield return i;
        value >>= 1;
    }
}

如果您希望它是快,你可能会考虑返回列表与LT; INT方式&gt; 而不是

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

这篇关于枚举最快的方式,通过开启一个整数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆