您的位置:首页 > 其它

位运算--权限运用

2018-03-27 15:53 260 查看
今天读了fastjson的源码,受益良多.那位运算来分享一下.
以前一直不明白位运算有什么用,现在明白位运算在做权限的时候用处很大.
1. 初始化权限int select=1;//0001
int insert=2;//0010
int update=4;//0100
int delete=8;//10002. 获取权限
如A用户仅有读写操作,(至于怎么知道他有读写操作权限,这里就不描述了),那么他的权限int值为int p=0;
p |= select;
P |= insert;3. 判断权限
在上1步已经获取了权限的数字p,则用下面的方法判断是否有权限; if((p&select)==select){
System.out.println("select");
}else {
System.out.println("can not select");
}
if ((p & insert) == insert) {
System.out.println("insert");
} else {
System.out.println("can not insert");
}
if((p&update)==update){
System.out.println("update");
}else{
System.out.println("can not update");
}
if ((p & delete) == delete) {
System.out.println("delete");
} else {
System.out.println("can not delete");
}4. 小结
这里select,insert,update,delete 只是示例,应用的时候可以将他们设置为枚举,利用枚举的ordinal()方法,
再用1<<ordinal()确定权限的数值,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  位运算 权限