Counting the number of flags set on an enumeration

后端 未结 9 1339
孤街浪徒
孤街浪徒 2021-02-18 20:17

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 t

相关标签:
9条回答
  • 2021-02-18 21:08

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

    Here's the code for anyone else:

        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;
        }
    
    0 讨论(0)
  • 2021-02-18 21:10
    int count = Enum.GetValues(typeof(Skills)).Length;
    
    0 讨论(0)
  • 2021-02-18 21:16
    <FlagsAttribute()> _
    Public Enum Skills As Byte
        None = 0
        Skill1 = 1
        Skill2 = 2
        Skill3 = 4
        Skill4 = 8
        Skill5 = 16
        Skill6 = 32
        Skill7 = 64
        Skill8 = 128
    End Enum
    
    
        Dim x As Byte = Skills.Skill4 Or Skills.Skill8 Or Skills.Skill6
        Dim count As Integer
        If x = Skills.None Then count = 0 Else _
            count = CType(x, Skills).ToString().Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries).Count
    

    depends on the definition of "better".

    the check for Skills.None is required because if no bits are on, the string() returns Skills.None which results in a count of 1. this would work the same for integer, long, and their unsigned relatives.

    0 讨论(0)
提交回复
热议问题