21

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.

e.g.

[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?

Michael Meadows
  • 27,796
  • 4
  • 47
  • 63
Ian
  • 33,605
  • 26
  • 118
  • 198
  • Would you be more clear whether you are trying to figure out total number of flags in Skills Enum itself? or number of Skills enum value applied on "skills"? – dance2die Mar 24 '09 at 12:47
  • I definitely misread this. It looks like he's trying to count the number of bits that are on, not the number of items in the enumeration. I deleted my post. – John Feminella Mar 24 '09 at 12:48
  • Sorry for being unclear. Indeed I am trying to count the number of active skills passed into the Count method. Will edit the question slightly to make it clearer. – Ian Mar 24 '09 at 12:51
  • @Ian: I edited the post title to make this clearer. Feel free to rollback if you think it's not an accurate reflection of what you wanted. – John Feminella Mar 24 '09 at 12:52
  • You can use BitOperations.PopCount since .NET Core 3.0: https://learn.microsoft.com/en-us/dotnet/api/system.numerics.bitoperations.popcount – Skarllot Jun 17 '21 at 21:40

9 Answers9

31

The following code will give you the number of bits that are set for a given number of any type varying in size from byte up to long.

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

This code is very efficient as it only iterates once for each bit rather than once for every possible bit as in the other examples.

stevehipwell
  • 56,138
  • 6
  • 44
  • 61
  • 1
    @JohannGerell You might like the [answer](http://stackoverflow.com/a/42557518/197591) I just posted for your goodie bag! :) – Neo Mar 02 '17 at 14:05
11

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;
    }
Ian
  • 33,605
  • 26
  • 118
  • 198
  • But Flags enums are limited to 32 options anyway according to the spec so that's not a problem. – Ian Apr 29 '16 at 12:56
  • 3
    If anybody's interested this is called Hemming wieght. More details from wikipedia: https://en.wikipedia.org/wiki/Hamming_weight – SOReader May 05 '17 at 19:25
  • enum can be inherited from long – Slava Apr 26 '18 at 15:56
  • You can use BitOperations.PopCount since .NET Core 3.0: https://learn.microsoft.com/en-us/dotnet/api/system.numerics.bitoperations.popcount – Skarllot Jun 17 '21 at 21:41
9

A very concise way to do it using BitArray and LINQ:

public static int Count(Skills skillsToCount)
{
    return new BitArray(new[] {(int)skillsToCount}).OfType<bool>().Count(x => x);
}
Neo
  • 4,145
  • 6
  • 53
  • 76
7

If you're targeting .NET Core 3.0 or above, you can use BitOperations.PopCount(), it operates in uint or ulong and returns the number of 1 bits.

If your CPU supports SSE4, it'll use the POPCNT CPU instruction, otherwise it'll use a software fallback.

public static int Count(Skills skillsToCount)
{
   return BitOperations.PopCount((ulong)skillsToCount);
}
Magnetron
  • 7,495
  • 1
  • 25
  • 41
3

The count is equivalent to counting how many bits are set to 1 in the integer value of the enum.

There are very fast ways of doing this in C/C++, which you can adapt to C#:

e.g.

int bitcount(unsigned int n) {
   /* works for 32-bit numbers only    */
   /* fix last line for 64-bit numbers */

   register unsigned int tmp;

   tmp = n - ((n >> 1) & 033333333333)
           - ((n >> 2) & 011111111111);
   return ((tmp + (tmp >> 3)) & 030707070707) % 63;
}

Taken from here.

EDIT
Provided link is dead. Found another one that probably contains the same content.

SOReader
  • 5,697
  • 5
  • 31
  • 53
Assaf Lavie
  • 73,079
  • 34
  • 148
  • 203
  • That's more what I'm after yes. Although can't quite get it working yet. – Ian Mar 24 '09 at 13:05
  • You might have a better understanding of this that me... Currently I'm trying to use a UInt32 but 033333333333 etc won't cast to a UInt32. – Ian Mar 24 '09 at 13:12
  • Using that site I managed to find a post with slightly different approach that got me to the solution. Thanks Assaf. – Ian Mar 24 '09 at 13:28
  • 1
    i managed to get the VB version to work after changing the mask's to octal. – dbasnett Mar 24 '09 at 17:40
  • we have more on this algorithm on-site, so there is no need to follow up those dead external links: https://stackoverflow.com/q/109023/1132334 – Cee McSharpface Aug 07 '17 at 16:17
2

There's a straight-forward way using functional programming (LINQ):

var skillCount = Enum
    .GetValues(typeof(Skills))
    .Cast<Enum>()
    .Count(skills.HasFlag);

It might be a bit slower than the bit-juggling solutions but it has a constant run-time and is more intuitive.

While GetValues still allocates, there is a good chance that the compiler optimizes this away.

Kai Giebeler
  • 517
  • 6
  • 12
0
<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.

dbasnett
  • 11,334
  • 2
  • 25
  • 33
0

the only reason to use this method is if the flags are not contiguous and if flags will be added periodically.

<FlagsAttribute()> _
Public Enum Skills As Integer
    Skill1 = CInt(2 ^ 0) 'bit 0
    Skill2 = CInt(2 ^ 1)
    Skill3 = CInt(2 ^ 2)
    Skill4 = CInt(2 ^ 3)
    Skill5 = CInt(2 ^ 4)
    Skill6 = CInt(2 ^ 5)
    Skill7 = CInt(2 ^ 6)
    Skill8 = CInt(2 ^ 7)
    Skillx = CInt(2 ^ 10) 'bit 10, some bits were skipped
End Enum


    Dim mySkills As Integer = Skills.Skillx Or Skills.Skill4 Or Skills.Skill8 Or Skills.Skill6
    Dim count As Integer 'count of bits on
    count = CType(mySkills, Skills).ToString().Split(New Char() {","c}, _
                                                     StringSplitOptions.RemoveEmptyEntries).Count

if "better" means faster this ain't ;) it.

dbasnett
  • 11,334
  • 2
  • 25
  • 33
-4
int count = Enum.GetValues(typeof(Skills)).Length;
Lee
  • 1,125
  • 6
  • 7