什么是最快的方式计数设置位在UInt32在C# [英] What is the fastest way to count set bits in UInt32 in C#
本文介绍了什么是最快的方式计数设置位在UInt32在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在不使用查找表的情况下,在UInt32中计数设置位数(即计数1的数目)的最快方法是什么?是否有办法在O(1)?
What is the fastest way to count the number of set bits (i.e. count the number of 1s) in an UInt32 without the use of a look up table? Is there a way to count in O(1)?
推荐答案
是重复的:
how-to-implement-bitcount-using-only-bitwise-operators
或
best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer
这个问题有很多解决方案。我使用的是:
And there are many solutions for that problem. The one I use is:
int NumberOfSetBits(int i)
{
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
这篇关于什么是最快的方式计数设置位在UInt32在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文