How to check how many bit / bit mask numbers contains

I store all my equipped guns with a bit flag and just wondered if it was possible to check how many numbers were in the bit flag.

eg.

13 will contain 1, 4, and 8

Note: I am new to bit flags, so my question may not make much sense, or I might use the wrong terminology, if so, just let me know and I will be happy to change it.

+4
source share
2 answers

Since you are asking:

How many numbers are there in a bit flag?

This should work:

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

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

    return count;
}
+2
source

I quickly wrote a method that does exactly what you want, of course, not the best:

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

How it works:

. "1" s 2 . - "1" .

EDIT:

, :

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

Source: https://habr.com/ru/post/1663458/


All Articles