枚举中两个变量中的标志数



我有以下枚举:

[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
}

我有以下一段代码:

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

如何获取变量first但也second变量中的标志数?

我想要的结果:

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

尝试了按位运算,但我认为我无法从中获得此值。

您可以将 AND 标志放在一起,然后计算设置位数(这称为整数的"汉明权重")。

一种计算设置位的方法(有很多,这是我从网上抓到的):

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

所以对于你的问题:

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

和:

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

如果您想知道该特定实现的工作原理,请参阅此处。

另一个可能的答案是通过BitArray类

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

最新更新