Alex Rivera | Logout

how to convert an int to a bitmask?

Asked 2009-11-02T17:12:27.470
13

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?

Edit
Report

1 Answer

5

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);
}
answered 2009-11-02T17:15:50.560

Your Answer