1

I have the following enum:

[Flags]
public enum Letter
{
    NONE  = 0,
    A = 1, 
    B = 2, 
    C = 4,
    A_B = A | B,
    A_C = A | C,
    B_C = B | C,
    ALL = A | B | C
}

And I have the following piece of code:

Letter first = Letter.A_B;
Letter second = Letter.B_C;

How to get the number of flags that is in first variable but also in second variable?

The result I would like to have:

Letter first = Letter.A_B;
Letter second = Letter.B_C;
int numberOfSameFlags = ...; // should return 1 in this example

Letter first = Letter.A_B;
Letter second = Letter.ALL;
int numberOfSameFlags = ...; // should return 2 in this example

I tried bitwise operations but I don't think I can get this value from that.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Moussamoa
  • 417
  • 1
  • 4
  • 19
  • If you want to use *only* bitwise operations, you can do it [this](https://stackoverflow.com/questions/3815165/how-to-implement-bitcount-using-only-bitwise-operators) way. – Bradley Uffner Oct 13 '17 at 14:17

2 Answers2

3

You can AND the flags together and then count the number of set bits (this is known as the "Hamming Weight" of an integer).

One way you can count the set bits (there are many, this is one I grabbed off the net):

public static int HammingWeight(int i)
{
     i = i - ((i >> 1) & 0x55555555);
     i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
     return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}

So for your problem:

Letter first = Letter.A_B;
Letter second = Letter.B_C;
Console.WriteLine(HammingWeight((int)first & (int)second));

And:

Letter first = Letter.A_B;
Letter second = Letter.ALL;
Console.WriteLine(HammingWeight((int)first & (int)second));

If you want to know how that particular implementation works, see here.

Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
2

Another possible answer is through the BitArray class

int f = Convert.ToInt32(first);
int s = Convert.ToInt32(second);
BitArray bit = new BitArray(System.BitConverter.GetBytes(f & s));
Console.WriteLine(bit.Cast<bool>().Count(x => x));
Steve
  • 213,761
  • 22
  • 232
  • 286