简体   繁体   English

从位掩码返回一组对象

[英]Return a collection of objects from a bitmask

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) 我“需要”一种更好的方法来从位掩码生成一个对象集合(一个ushort传递,在二进制形式上它被解释为一个掩码)

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

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

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

It could look like you want an Enum with the [Flags] attribute. 看起来你想要一个带有[Flags]属性的Enum。 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
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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM