http://blog.csdn.net/jjwwmlp456/article/details/38737721
http://blog.csdn.net/jjwwmlp456/article/details/38737721
http://blog.csdn.net/jjwwmlp456/article/details/38737721
http://blog.csdn.net/jjwwmlp456/article/details/38737721http://blog.csdn.net/jjwwmlp456/article/details/38737721
- public class Demo {
- static int a = 0x1;
- static int b = 0x2;
- static int c = 0x4;
- static int d = 0x8;
- static int e = 0x10;
- static int f = 0x20;
- static int g = 0x40;
- static int h = 0x80;
- static int i = 0x100;
- static int j = 0x200;
- public static void main(String[] args) {
- System.out.println(a);
- System.out.println(b);
- System.out.println(c);
- System.out.println(d);
- System.out.println(e);
- System.out.println(f);
- System.out.println(g);
- System.out.println(h);
- System.out.println(i);
- System.out.println(j);
- }
- }
输出结果
- 1
- 2
- 4
- 8
- 16
- 32
- 64
- 128
- 256
- 512
上面使用16进制0x的形式,定义了一些二进制的数据,发现他们非常有规律,1 2 4 8 .... 进位时后面加0就是下一个二进制数。书写简单
它们在二进制的表示为1,10,100,1000,10000.... 类似这样只有一位有效位,其他位全为0
再来看下面
- System.out.println(h | j);
- System.out.println((h | j) & h);//与比或的 优先级高
- System.out.println((h | j) & j);
- System.out.println(h & j);
输出结果
- 640
- 128
- 512
- 0
当a不等于b时,按位与(&)时,结果直接就为0
当a=b时,不管按位与还是按位或 那结果还是a
综上,所以源码中很多就如此应用了这一效果。 一般有一个 0x0的空、无的状态, 再有 1 2 4 8 ... 这样的二进制数的状态
用按位或: 可以将 多个状态累加 类似 flag1 | flag2 | flag3 ,得到的结果在二进制中的表示可能为101001
用按位与: 可以将 内部的一个记录自身当前状态的变量 按位与 一个定义的状态值 类似 mCurFlag & FLAG1
当结果不为0时或者说等于FLAG1时, 表示含有FLAG1这个状态