Returns a collection of objects from a bitmask

I "need" the best way to generate a collection of objects from a bitmask (passed by the user, in binary form it is interpreted as a mask)

A simple, not elegant solution:

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) };  

//etc...

code>

+3
source share
4 answers

Try to execute

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;
}
+6
source

untested, uses fewer iterations than other solutions; -)

List<Thing> things = new List<Thing>();
for (int n=0;n<4;n++)
{
   int val = Math.Pow(2,i);
   if ((mask & val) == val)
   {
       things.Add(new Thing(val));
   }
}
return things.ToArray();
+1
source

It might seem that you want Enum with the [Flags] attribute. You would have:

[Flags]
enum ThingType
{
    THING1 = 1,
    THING2 = 2,
    THING2 = 4,
    THING3 = 8,
    THING4 = 16
}

This allows you to do something like

ThingType x = ThingType.THING1 | ThingType.THING3;

And

int x = 3;
ThingType y = (ThingType)x; // THING1 | THING2
+1
source
List<Thing> Things = new List<Thing>();
ushort msk = mask;
for (int 0 = 0; i < 16; ++i)
{
    if ((msk & 1) != 0)
    {
        Things.Add(new Thing(i));
    }
    msk >>= 1;
}
return Things.ToArray();
0
source

Source: https://habr.com/ru/post/1770965/


All Articles