/**
* 按位与 : &
* 按位或 : |
*/
public class Demo {
/**
* 按位与: 为什么(5 & 9)的值等于1
* 按位或: 为什么(5 | 9)的值等于13
*/
@Test
public void test() {
System.out.println(5 & 9); // 1
System.out.println(5 | 9); // 13
System.out.println(Integer.toBinaryString(5)); // 0101
System.out.println(Integer.toBinaryString(9)); // 1001
/*
5的二进制数据:0101
9的二进制数据:1001
1)与操作&:从左向右,上下数字比较,两个都是1,相同位才赋值为1
0101
1001
-----
0001
得出结果:0001(二进制数据),转为十进制后的值为1
2)或操作|:从左向右,上下数字比较,有一个是1,相同位就赋值为1
0101
1001
-----
1101
得出结果:1101(二进制数据),转为十进制后的值为13
*/
}
/**
* 按位与(&)、按位或(|)的使用场景
*/
@Test
public void test1() {
// 配合数字1,2,4,8..进行使用
// 假设有5个类别
int type1 = 1;
int type2 = 2;
int type3 = 4;
int type4 = 8;
int type5 = 16;
// 装入type1,type2,type3,type5
int types = type1 | type2 | type3 | type5; // 未装入type4
System.out.println(types); // 23
// 判断集合中是否有某个类别
System.out.println((types & type1) == type1); // true
System.out.println((types & type2) == type2); // true
System.out.println((types & type3) == type3); // true
System.out.println((types & type4) == type4); // false
System.out.println((types & type5) == type5); // true
}
}