嗨,我需要删除Java中的标志.我有以下常量:
public final static int OPTION_A = 0x0001;
public final static int OPTION_B = 0x0002;
public final static int OPTION_C = 0x0004;
public final static int OPTION_D = 0x0008;
public final static int OPTION_E = 0x0010;
public final static int DEFAULT_OPTIONS =
OPTION_A | OPTION_B | OPTION_C | OPTION_D | OPTION_E;
Run Code Online (Sandbox Code Playgroud)
我想删除默认选项中的OPTION_E.为什么以下代码不正确?
// remove option E from defaul options:
int result = DEFATUL_OPTIONS;
result |= ~OPTION_E;
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 48
|=执行按位或,所以你有效地"添加"除了之外的所有标志OPTION_E.你想&=(按位和)说你要保留除以下之外的所有标志OPTION_E:
result &= ~OPTION_E;
Run Code Online (Sandbox Code Playgroud)
但是,更好的方法是使用枚举并EnumSet从以下开始:
EnumSet<Option> options = EnumSet.of(Option.A, Option.B, Option.C,
Option.D, Option.E);
options.remove(Option.E);
Run Code Online (Sandbox Code Playgroud)
A.H*_*.H. 10
你必须写
result &= ~OPTION_E;
Run Code Online (Sandbox Code Playgroud)
更长的解释:
你必须考虑一下:
~OPTION_E // 0x0010 -> 0xFFEF
DEFATUL_OPTIONS // -> 0x001F
0xFFEF | 0x001F // -> 0xFFFF
0XFFEF & 0x001F // -> 0x000F
Run Code Online (Sandbox Code Playgroud)
将OR永远不会清楚1位,这将至多设置更多一些.
AND另一方面将清除位.
您应该使用and运算符而不是or:
result &= ~OPTION_E;
Run Code Online (Sandbox Code Playgroud)
考虑它的一种方法是|= 设置位而&= 清除位:
result |= 1; // set the least-significant bit
result &= ~1; // clear the least-significant bit
Run Code Online (Sandbox Code Playgroud)