Counting the number of flags set on an enumeration

后端 未结 9 1346
孤街浪徒
孤街浪徒 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:06

    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.

提交回复
热议问题