天天看點

BigInteger權限判斷

1、上篇文章已經解析了BigInteger.testBit(int n)與setBit(int n)

http://blog.csdn.net/u014520797/article/details/64122211

2、在進行開發權限系統時可以使用BigInteger.setBit(int n)與testBit(int n)進行權限設定和權限判斷

3、代碼

public static void main(String[] args) {
		BigInteger bi = new BigInteger("0"); 
		bi =bi.setBit(1);
		bi =bi.setBit(2);
		bi =bi.setBit(3);
		bi =bi.setBit(6);
		
		Boolean b1, b2,b3,b5;
		b1 = bi.testBit(1);
		b2 = bi.testBit(2);
		b3 = bi.testBit(3);
		b5 = bi.testBit(7);
		
		String str1 = "Test Bit on " + bi + " at index 1 returns " +b1;
		String str2 = "Test Bit on " + bi + " at index 2 returns " +b2;
		String str3 = "Test Bit on " + bi + " at index 3 returns " +b3;
		String str5 = "Test Bit on " + bi + " at index 7 returns " +b5;
		
		System.out.println( str1 );
		System.out.println( str2 );
		System.out.println( str3 );
		System.out.println( str5 );
	}
           

結果

Test Bit on 78 at index 1 returns true
Test Bit on 78 at index 2 returns true
Test Bit on 78 at index 3 returns true
Test Bit on 78 at index 7 returns false
           

4、解釋

//在權限系統中,當一個權限資源的id為123456789.....
//當A擁有23資源的權限,那麼就可以bi =bi.setBit(2或3或其他權限id),然後再去用bi.testBit(2或3或其他權限id)去驗證,
           
//當擁有該權限時,便會傳回true
//當B擁有456資源的權限,...........
//當C擁有789資源的權限,...........
			
//當然  也可不需要一個的去設定bi =bi.setBit(int n),比如A擁有2,3權限時,那麼他的權限值為12(即1100),
//是以可以用new BigInteger("12").setBit(2或3或其他權限id)
           

5、如果有不懂,可以看上一篇的方法解釋