Java 位操作
1.位左移(符号位不变)<<
2.位右移(符号位不变)>>
3.无符号的位移(空位补零,不考虑符号位)<<<
‘>>>’
4.或|
5.与&
6.按位取反~
7.异或^
用途
用途有点类似控制器上的拨码开关.00001001001
.一般来说,用0代表无,1代表有.每一个符号位代表一种权限.这种应用在多权限的场景下很容易解决N权限的问题.
Java 代码
判断方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16//复合权限判断
private static boolean isHasAllAuthority(long ready,long authority){
return (ready & authority) == authority ? true :false ;
}
//添加权限
private static long addAuthority(long ready,long authority){
return ready | authority;
}
//删除权限
private static long removeAuthority(long ready,long authority){
return (ready | authority) ^ authority ;
}
测试方法1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23long pp1 = 1<<1 ;
long pp2 = 1<<2 ;
long pp3 = 1<<3 ;
long pp4 = 1<<4 ;
//初始化权限
long ready = 0L ;
//添加1,4权限
ready = addAuthority(ready,pp1) ;
ready = addAuthority(ready,pp4) ;
//删除1,3权限
ready = removeAuthority(ready,pp1|pp3) ;
//判断是否拥有1权限
System.out.println("判断是否拥有1权限" + isHasAllAuthority(ready,pp1));
//判断是否拥有3权限
System.out.println("判断是否拥有3权限" + isHasAllAuthority(ready,pp3));
//判断是否拥有4权限
System.out.println("判断是否拥有4权限" + isHasAllAuthority(ready,pp4));
//判断是否拥有1,4权限
System.out.println("判断是否拥有1,4权限" + isHasAllAuthority(ready,pp1|pp4));
结果1
2
3
4
5
6判断是否拥有1权限false
判断是否拥有3权限false
判断是否拥有4权限true
判断是否拥有1,4权限false
Process finished with exit code 0