如何检查位标志/位掩码包含多少个数字

时间:2016-12-11 17:40:30

标签: c# unity3d

我正在使用位标志存储我所有装备好的枪支,并且只是想知道是否可以检查位标志中包含多少个数字。

e.g。 :

13将包含1,4和8

注意: 我是新手,因此我的问题可能没有多大意义,或者我可能使用了错误的术语,如果是这样,请告诉我,我将很乐意改变它。

2 个答案:

答案 0 :(得分:2)

因为你问:

  

位标志中包含多少个数字?

这应该有效:

int CountBits(int n)
{
    int count = 0;
    do
    {
        int has = n & 1;
        if (has == 1) 
        {
            count ++ ;
        }

    } while((n >>= 1) != 0);

    return count;
}

答案 1 :(得分:0)

我很快写了一个方法,它完全符合你的要求,当然不是最好的方法:

public static List<int> DecomposeBitFlag(int flag) {
    var bitStr = Convert.ToString(flag, 2);
    var returnValue = new List<int>();
    for(var i = 0 ; i < bitStr.Length ; i++) {
        if (bitStr[bitStr.Length - i - 1] == '1') {
            returnValue.Add((int)Math.Pow(2, i));
        }
    }
    return returnValue;
}

工作原理:

我首先将整数参数转换为二进制字符串。对于字符串中的每个“1”,将2的幂i加到返回值列表中。 i是反向字符串中“1”的索引。

编辑:

如果您只想知道位数,可以这样做:

public static int BitFlagBitCount(int flag) {
    var bitStr = Convert.ToString(flag, 2);
    return bitStr.Count(c => c == '1');
}
相关问题