Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return a collection of objects from a bitmask

Tags:

c#

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 ......

like image 361
MexDev Avatar asked Jan 30 '26 06:01

MexDev


2 Answers

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;
}
like image 86
JaredPar Avatar answered Jan 31 '26 20:01

JaredPar


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
like image 28
Jeremy Elbourn Avatar answered Jan 31 '26 21:01

Jeremy Elbourn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!