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?
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.
Found it
BitArray bits = new BitArray(System.BitConverter.GetBytes(showGroup.Value));
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With