I "need" a better way to generate a collection of objects from a bitmask (a ushort passed, on binary form it's interpreted as a mask)
The easy, non elegant solution would be:
public static Things[] Decode(ushort mask)
{
switch (mask)
{
case 1: // 1
return new[] { new Thing(0) };
case 2: //10
return new[] { new Thing(1) };
case 3: // 11
return new[] { new Thing(1), new Thing(0) };
case 4: // 100
return new[] { new Thing(2) };
case 5: // 101
return new[] { new Thing(2), new Thing(0) };
// so on ......
Try the following
public static List<Thing> Decode(ushort mask) {
var list = new List<Thing>();
for ( var index = 0; index < 16; index++ ) {
var bit = 1 << index;
if ( 0 != (bit & mask) ) {
list.Add(new Thing(index));
}
}
return list;
}
It could look like you want an Enum with the [Flags] attribute. You would have:
[Flags]
enum ThingType
{
THING1 = 1,
THING2 = 2,
THING2 = 4,
THING3 = 8,
THING4 = 16
}
This lets you do things like
ThingType x = ThingType.THING1 | ThingType.THING3;
And also
int x = 3;
ThingType y = (ThingType)x; // THING1 | THING2
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