Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert an int to a bitmask?

Tags:

c#

.net

Is there a way to convert an int to a bitmask?

example:

int i = 33;

should be converted to (not sure of the datatype)

bool[] bitmask = new[] {true, false, false, false, false, true};

Update
In reaction to most answers:

I need to do this:

BitArray bits = new BitArray(BitConverter.GetBytes(showGroup.Value));
List<String> showStrings = new List<string>();
for (int i = 0; i < bits.Length; i++)
{
    if(bits[i])
        showStrings.Add((i+1).ToString().PadLeft(2, '0'));
}

How would that go without converting it to a bitarray?

like image 709
Boris Callens Avatar asked Nov 02 '09 17:11

Boris Callens


3 Answers

An int already is a bitmask. If you want to twiddle the bits, you can use bitwise operators freely on ints. If you want to convert the int to an enum that has the Flags attribute, a simple cast will suffice.

like image 142
JSBձոգչ Avatar answered Oct 20 '22 00:10

JSBձոգչ


Found it

BitArray bits = new BitArray(System.BitConverter.GetBytes(showGroup.Value));
like image 20
Boris Callens Avatar answered Oct 19 '22 22:10

Boris Callens


You could construct a bool[32] and loop through all bits in the int, masking it with 2^(loop counter) and setting the bools in the array appropriately.

Are you sure you need this, though? Most operations with bitmasks work with ints directly.

To answer the question in your edit:

int val = 35;
List<string> showStrings = new List<string>();
for (int i = 0; i < 32; i++)
{
    if (( (1 << i) & val) > 0)
    {
        showStrings.Add((i + 1).ToString().PadLeft(2, '0'));
    }
}

prints:

01  
02  
06 

Not the most obvious solution if you're not used to bit arithmetic, true. Mask each bit in the integer value with 2^(bit-index), and if the resulting value is greater than zero (indicating that the bit at that index is set), do something. 1 << i (left-shifting) is equivalent to 2^i, and may have the same performance characteristics once JITted, but I'm used to this form.

Expressed as a macro-like method:

bool IsSet(int val, int index)
{
    return (( (1 << (index-1)) & val) > 0);
}
like image 39
Michael Petrotta Avatar answered Oct 19 '22 22:10

Michael Petrotta