简体   繁体   English

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

[英]Number of flags that are in two variables in enum

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? 如何获得first变量中以及second变量中标志的数量?

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. 我尝试了按位运算,但我认为无法从中获得此值。

You can AND the flags together and then count the number of set bits (this is known as the "Hamming Weight" of an integer). 您可以将这些标志与在一起,然后计算设置的位数(这被称为整数的“ Hamming Weight” )。

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 . 如果您想知道特定实现的工作原理, 请参见此处

Another possible answer is through the BitArray class 另一个可能的答案是通过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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM