gpt4 book ai didi

c# - 计算枚举上设置的标志数

转载 作者:IT王子 更新时间:2023-10-29 04:47:09 25 4
gpt4 key购买 nike

我相信一定有更好的方法来做到这一点。我正在尝试对 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;
}

我敢肯定肯定有更好的方法来做到这一点,但一定是精神障碍。谁能建议更好的解决方案?

最佳答案

以下代码将为您提供为给定数量的任何类型设置的位数,大小从字节到长不等。

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;
}

此代码非常高效,因为它只为每个位迭代一次,而不是像其他示例中那样为每个可能的位迭代一次。

关于c# - 计算枚举上设置的标志数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/677204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com