我相信一定有更好的方法来做这件事。我正在尝试对Flags枚举执行计数操作。在我遍历所有可能的值并计算成功的and操作之前。
例如:
[Flags]
public enum Skills
{
None = 0,
Skill1 = 1,
Skill2 = 2,
Skill3 = 4,
Skill4 = 8,
Skill5 = 16,
Skill6 = 32,
Skill7 = 64,
Skill8 = 128
}
public static int Count(Skills skillsToCount)
{
Skills skill;
for (int i = 0; i < SkillSet.AllSkills.Count; i++)
{
skill = SkillSet.AllSkills[i];
if ((skillsToCount & skill) == skill && skill != Skills.None)
count++;
}
return count;
}我相信肯定有更好的方法来做到这一点,但一定是精神障碍。有没有人能建议一个更好的解决方案?
发布于 2009-03-24 13:20:00
在看了这个网站后,Assaf建议我设法找到一个略有不同的解决方案,这是我为Int32工作的。
下面是其他人的代码:
internal static UInt32 Count(this Skills skills)
{
UInt32 v = (UInt32)skills;
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
UInt32 c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
return c;
}发布于 2009-08-26 08:47:59
下面的代码将给出为给定数量的任意类型设置的位数,这些类型的大小从字节到长整型不等。
public static int GetSetBitCount(long lValue)
{
int iCount = 0;
//Loop the value while there are still bits
while (lValue != 0)
{
//Remove the end bit
lValue = lValue & (lValue - 1);
//Increment the count
iCount++;
}
//Return the count
return iCount;
}这段代码非常高效,因为它只对每个比特迭代一次,而不是像在其他示例中那样,为每个可能的比特迭代一次。
发布于 2017-03-02 22:03:31
使用BitArray和LINQ的一种非常简洁的方法:
public static int Count(Skills skillsToCount)
{
return new BitArray(new[] {(int)skillsToCount}).OfType<bool>().Count(x => x);
}https://stackoverflow.com/questions/677204
复制相似问题