Hi I need to remove a flag in Java. I have the following constants:
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;
I want to remove, for example OPTION_E from default options. Why is not the following code correct?
// remove option E from defaul options:
int result = DEFATUL_OPTIONS;
result |= ~OPTION_E;
|=
performs a bitwise or , so you're effectively "adding" all the flags other than OPTION_E
. You want &=
(bitwise and ) to say you want to retain all the flags other than OPTION_E
:
result &= ~OPTION_E;
However, a better approach would be to use enums and EnumSet
to start with:
EnumSet<Option> options = EnumSet.of(Option.A, Option.B, Option.C,
Option.D, Option.E);
options.remove(Option.E);
You must write
result &= ~OPTION_E;
Longer explanation:
You must think in bits:
~OPTION_E // 0x0010 -> 0xFFEF
DEFATUL_OPTIONS // -> 0x001F
0xFFEF | 0x001F // -> 0xFFFF
0XFFEF & 0x001F // -> 0x000F
The OR
will never clear 1
bits, it will at most set some more. AND
on the other hand will clear bits.
You should use the and
operator instead of or
:
result &= ~OPTION_E;
One way to think about it is that |=
sets bits whereas &=
clears bits:
result |= 1; // set the least-significant bit
result &= ~1; // clear the least-significant bit
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.