按位与(&)和按位或(|)

按位与(&)和按位或(|),第1张

按位与(&)和按位或(|)
/**
* 按位与 : &
* 按位或 : |
*/
public class Demo { /**
* 按位与: 为什么(5 & 9)的值等于1
* 按位或: 为什么(5 | 9)的值等于13
*/
@Test
public void test() {
System.out.println(5 & 9); //
System.out.println(5 | 9); // System.out.println(Integer.toBinaryString(5)); //
System.out.println(Integer.toBinaryString(9)); // /*
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
} }

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/585494.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存