Counting the number of flags set on an enumeration

后端 未结 9 1344
孤街浪徒
孤街浪徒 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 20:59

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

提交回复
热议问题