setBit
/**
* Returns a BigInteger whose value is equivalent to this BigInteger
* with the designated bit set. (Computes {@code (this | (1<<n))}.)
*
* @param n index of bit to set.
* @return {@code this | (1<<n)}
* @throws ArithmeticException {@code n} is negative.
*/
public BigInteger setBit(int n)
其实际作用就是将数n的二进制形式的第 n+1位设置为1。
BigInteger num = new BigInteger("12");
BigInteger newNum = num.setBit(1); // 14
// 12 的二进制 1 1 0 0
// 1 << 1 即1左移1位 0 0 1 0
// 两个做或运算 就是 1 1 1 0 即 14
testBig
/**
* Returns {@code true} if and only if the designated bit is set.
* (Computes {@code ((this & (1<<n)) != 0)}.)
*
* @param n index of bit to test.
* @return {@code true} if and only if the designated bit is set.
* @throws ArithmeticException {@code n} is negative.
*/
public boolean testBit(int n)
实际就是判断数n 的二进制形式的第 n+1 为是否不为0
BigInteger num = new BigInteger("12);
BigInteger newNum = num.setBit(1); // 14
newNum.testBit(1); // true
设置权限辅助工具
public class RightsHelper {
/**
* 利用BigInteger对权限进行2的权的和计算
* @param rights int型权限编码数组
* @return 2的权的和
*/
public static BigInteger sumRights(int[] rights){
BigInteger num = new BigInteger("0");
for(int i=0; i<rights.length; i++){
num = num.setBit(rights[i]);
}
return num;
}
/**
* 利用BigInteger对权限进行2的权的和计算
* @param rights String型权限编码数组
* @return 2的权的和
*/
public static BigInteger sumRights(String[] rights){
BigInteger num = new BigInteger("0");
for(int i=0; i<rights.length; i++){
num = num.setBit(Integer.parseInt(rights[i]));
}
return num;
}
/**
* 测试是否具有指定编码的权限
* @param sum
* @param targetRights
* @return
*/
public static boolean testRights(BigInteger sum,int targetRights){
return sum.testBit(targetRights);
}
/**
* 测试是否具有指定编码的权限
* @param sum
* @param targetRights
* @return
*/
public static boolean testRights(String sum,int targetRights){
if(Tools.isEmpty(sum))
return false;
return testRights(new BigInteger(sum),targetRights);
}
/**
* 测试是否具有指定编码的权限
* @param sum
* @param targetRights
* @return
*/
public static boolean testRights(String sum,String targetRights){
if(Tools.isEmpty(sum))
return false;
return testRights(new BigInteger(sum),targetRights);
}
/**
* 测试是否具有指定编码的权限
* @param sum
* @param targetRights
* @return
*/
public static boolean testRights(BigInteger sum,String targetRights){
return testRights(sum,Integer.parseInt(targetRights));
}
public static void main(String[] args) {
// 某用户拥有菜单id 1 2 3 5 7 8 的权限 即可得到他对应的权限值
BigInteger sum = sumRights(new int[]{1,2,3,5,7,8});
// 判断其是否拥有菜单id 2 的权限
testRights(sum,2); //true
// 判断其是否拥有菜单id 4 的权限
testRights(sum,4); //false
}
}