0000-0000
1000-0000
1111-1111
1*2^7=128
1*2^6=64
1*2^5=32
1*2^4=16
1*2^3=8
1*2^2=4
1*2^1=2
1*2^0=1
0000-0010
0000-0000
0000-0001
1111-1110
0000-0010
1111-1110
0000-0001
0000-0010
private static final int DISABLE = 0x0;
private static final int CLICKABLE = 1;
private static final int LONG_CLICKABLE = 2;
private static final int DRAGGABLE = 4;
private static final int START = 8;
private static final int END = 16;
public static void main(String[] args) {
int mState = 11;
mState |= DISABLE;
mState &= ~CLICKABLE;
mState |= LONG_CLICKABLE;
mState |= DRAGGABLE;
mState |= START;
mState &= ~END;
System.out.println("mState = " + ((mState & DISABLE) == DISABLE));
System.out.println("mState = " + ((mState & CLICKABLE) == CLICKABLE));
System.out.println("mState = " + ((mState & LONG_CLICKABLE) == LONG_CLICKABLE));
System.out.println("mState = " + ((mState & DRAGGABLE) == DRAGGABLE));
System.out.println("mState = " + ((mState & START) == START));
System.out.println("mState = " + ((mState & END) == END));
}
如上分析:
定义常量,需要是2的N次幂
中间变量mState可以是任意的值
经由mState和常量有如下变换
mState |= DISABLE;
那么之后再有如下变换
((mState & DISABLE) == DISABLE)结果为true
如果上述有此变换
mState &= ~DISABLE;
((mState & DISABLE) == DISABLE)结果为false