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
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.