Counting the number of flags set on an enumeration

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

    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.

提交回复
热议问题