如何检查是否设置了多个枚举标志?

编程入门 行业动态 更新时间:2024-10-24 04:49:46
本文介绍了如何检查是否设置了多个枚举标志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我只想知道是否设置了一个枚举标志,而不是哪一个。我目前的想法是检查它是否是2的幂。有没有更好的方式内置枚举类型?

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 }

推荐答案

它的一个位操作!

if ((myFoo & (myFoo -1)) != 0) //has more than 1 flag

该语句检查 myFoo 的值是否不是电源的两个。或者反之亦然,语句(myFoo&(myFoo -1))== 0 检查两个的权力。这个想法是,只有单个标志值才是两个。设置多个标志将导致两个值 myFoo 的无功。

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.

可以找到更多信息在这个答案中有类似的问题: stackoverflow/a/1662162/2404788 。

More information can be found in this answer to a similar question: stackoverflow/a/1662162/2404788.

有关位操作的更多信息,请访问 http:// en .wikipedia / wiki / Bitwise_operation

For more information about bit operations go to en.wikipedia/wiki/Bitwise_operation

更多推荐

如何检查是否设置了多个枚举标志?

本文发布于:2023-11-27 10:24:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637690.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   标志

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!