java后端和JS前端权限位运算

6 篇文章 0 订阅
<pre name="code" class="java">package com.zw.util;

/**
 * 权限数字的运算
 * @author andy.wang
 *
 */
public class Competence {

	/**
	 * 根据权限点得到权限的总和
	 * @param i
	 * @return
	 */
	public static Integer getProduct(Integer[] i){
		Integer x=0;
		if (i==null||i.length==0) {
			return x;
		}
		for (int j : i) {
			x=x+(int)Math.pow(2,j);
		}
		return x;
	}
	
	/**
	 * 添加一个权限点
	 * @param i
	 * @return
	 */
	public static Integer addProduct(Integer i,Integer y){
		return(i)|((int)Math.pow(2,y));
	}
	
	/**
	 * 移除一个权限点
	 * @param i
	 * @return
	 */
	public static Integer rmProduct(Integer i,Integer y){
		return(i)&~((int)Math.pow(2,y));
	}
	
	/**
	 * 合并两个权限值
	 * @param i
	 * @return
	 */
	public static Integer ergerProduct(Integer i,Integer y){
		return i|y;
	}
	
	/**
	 * 检查权限点是否在权限值中
	 * @param i
	 * @return
	 */
	public static boolean checkProduct(Integer i,Integer y){
		Integer x = (int)Math.pow(2,y);
		return x==(i&x);
	}
	
	public static void main(String[] args) {
		Integer[] ii = new Integer[]{1,2,4,6,8};
		Integer[] iii = new Integer[]{1,2,4,5};
		Integer comp = getProduct(ii);//计算出权限值
		Integer comp1 = getProduct(iii);//计算出权限值
		comp = ergerProduct(comp, comp1);//合并两个权限值 重复的权限合并也可以
		comp=addProduct(comp, 7);//添加一个额外的权限点
		comp=addProduct(comp, 7);//添加一个额外的权限点多次添加也没关系
		comp = rmProduct(comp, 5);//移除一个权限值
		comp = rmProduct(comp, 5);//移除一个权限值 多次移除也没关系
		System.out.println(checkProduct(comp, 1));//检查权限
		System.out.println(checkProduct(comp, 2));
		System.out.println(checkProduct(comp, 4));
		System.out.println(checkProduct(comp, 5));
		System.out.println(checkProduct(comp, 7));
		System.out.println(checkProduct(comp, 8));
		System.out.println(checkProduct(comp, 9));
	}
	
}
还有一个js版本的
//计算权限点总和
function getProduct(array) {
		var x = 0;
		if (array.length == 0) {
			return x;
		}
		for (var i=0;i<array.length;i++) {
			x = x + Math.pow(2, array[i]);
		}
		return x;
}
//为权限值添加一个权限点
function addProduct(i,y) {
	return (i) |  Math.pow(2, y);
}
//为权限值移除一个权限点
function rmProduct(i,y) {
	return (i) & ~  Math.pow(2, y);
}
//合并两个权限值
function ergerProduct(i,y) {
	return i | y;
}
//检查权限值中是否包含某个权限点
function checkProduct(i,y) {
	var x =Math.pow(2, y);
	return x==(i&x);
}









评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值