C语言 如何删除C中的标志?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3920307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:41:35  来源:igfitidea点击:

How can I remove a flag in C?

cbit-manipulationflags

提问by Aaron de Windt

There is a variable that holds some flags and I want to remove one of them. But I don't know how to remove it.

有一个变量包含一些标志,我想删除其中一个。但我不知道如何删除它。

Here is how I set the flag.

这是我设置标志的方法。

my.emask |= ENABLE_SHOOT;

回答by Dennis

Short Answer

简答

You want to do an Bitwise ANDoperation on the current value with a Bitwise NOToperation of the flag you want to unset. A Bitwise NOT inverts every bit (i.e. 0 => 1, 1 => 0).

您想对当前值执行按位 AND运算,并对要取消设置标志执行按位非运算。按位非反转每一位(即 0 => 1, 1 => 0)。

flags = flags & ~MASK;or flags &= ~MASK;.

flags = flags & ~MASK;flags &= ~MASK;

Long Answer

长答案

ENABLE_WALK  = 0    // 00000000
ENABLE_RUN   = 1    // 00000001
ENABLE_SHOOT = 2    // 00000010
ENABLE_SHOOTRUN = 3 // 00000011

value  = ENABLE_RUN     // 00000001
value |= ENABLE_SHOOT   // 00000011 or same as ENABLE_SHOOTRUN

When you perform a Bitwise AND with Bitwise NOT of the value you want unset.

当您对要取消设置的值执行按位 AND 与按位 NOT 时。

value = value & ~ENABLE_SHOOT // 00000001

you are actually doing:

你实际上是在做:

      0 0 0 0 0 0 1 1     (current value)
   &  1 1 1 1 1 1 0 1     (~ENABLE_SHOOT)
      ---------------
      0 0 0 0 0 0 0 1     (result)

回答by Ned Batchelder

my.emask &= ~(ENABLE_SHOOT);

to clear a few flags:

清除一些标志:

my.emask &= ~(ENABLE_SHOOT|SOME_OTHER|ONE_MORE);

回答by supercat

It's important to note that if the variable being manipulated is larger than an int, the value used in the 'and not' expression must be as well. Actually, one can sometimes get away with using smaller types, but there are enough odd cases that it's probably best to use type suffixes to make sure the constants are large enough.

重要的是要注意,如果被操作的变量大于 int,则 'and not' 表达式中使用的值也必须相同。实际上,有时可以使用较小的类型,但有足够多的奇怪情况,最好使用类型后缀来确保常量足够大。