计算枚举上设置的标志数 [英] Counting the number of flags set on an enumeration

查看:101
本文介绍了计算枚举上设置的标志数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,必须有一个更好的方法。我正在尝试对Flags枚举进行计数操作。在我提出所有可能的值并计算成功的AND运算之前。

I'm sure there must be a much better way of doing this. I'm trying to do a count operation on a Flags enum. Before I was itterating over all the possible values and counting the succesful AND operations.

例如

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

虽然我相信必须有更好的方法,但是一定患有精神障碍。有人可以建议一个更好的解决方案吗?

I'm sure there must be a better way of doing this though, but must be suffering from a mental block. Can anyone advise a nicer solution?

推荐答案

在网站上查看后,阿萨夫建议我设法找到一个稍微不同的解决方案

After looking on the site Assaf suggested I managed to find a slightly different solution that I got working for Int32's.

这是其他人的代码:

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

这篇关于计算枚举上设置的标志数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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