怎样检查是否多个枚举标志设置? [英] How do I check if more than one enum flag is set?
问题描述
我只是想知道,如果只有一个枚举标志设置,没有哪个。我现在的想法是,以检查它是否是2的幂是否有内置枚举类型更好的办法?
[旗]
枚举符
{
标志1 = 0×01,
标志2 = 0×02,
相当于Flag3 = 0×04,
Flag4的= 0×08,
Flag5 = 0×10,
Flag6 = 0x20的,
Flag7 = 0X40,
Flag8 = 0x80的
}
私人布尔ExactlynOneFlagSet(美孚myFoo)
{
变种X =(字节)myFoo;
则返回(x = 0!)及和放大器; ((X及(X - 1型))== 0); //检查是否2
}
如果(!ExactlynOneFlagSet(美孚myFoo))
{
//做些什么
} $ B电源$ b
它有点操作!
IF((myFoo&安培;!(myFoo -1))= 0)//已超过1标志
语句检查值 myFoo
不是权力中的两个。或者,反之,语句(myFoo及(myFoo -1))== 0
检查的两个电源。我们的想法是,只有单一的标志值将是两个电源。设置多个标志将导致 myFoo
两个值的非权力。
更多信息,可以发现在这个回答类似的问题: http://stackoverflow.com/a/1662162/2404788
有关位操作更多信息,请 http://en.wikipedia.org/wiki / Bitwise_operation
I just want to know if exactly one enum flag is set, not which ones. My current thinking is to check if it is a power of 2. Is there a better way built into enum types?
[Flags]
enum Foo
{
Flag1 = 0x01,
Flag2 = 0x02,
Flag3 = 0x04,
Flag4 = 0x08,
Flag5 = 0x10,
Flag6 = 0x20,
Flag7 = 0x40,
Flag8 = 0x80
}
private bool ExactlynOneFlagSet(Foo myFoo)
{
var x = (byte) myFoo;
return (x != 0) && ((x & (x - 1)) == 0); //Check if a power of 2
}
if(!ExactlynOneFlagSet(Foo myFoo))
{
//Do something
}
Its a Bit operation!
if ((myFoo & (myFoo -1)) != 0) //has more than 1 flag
The statement checks if the value of myFoo
is not power of two. Or, vice versa, the statement (myFoo & (myFoo -1)) == 0
checks for power of two. The idea is that only single flag values will be power of two. Setting more than one flag will result in a non power of two value of myFoo
.
More information can be found in this answer to a similar question: http://stackoverflow.com/a/1662162/2404788.
For more information about bit operations go to http://en.wikipedia.org/wiki/Bitwise_operation
这篇关于怎样检查是否多个枚举标志设置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!