使用BigInteger.setBit与BigInteger.testBit来实现权限控制

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011548068/article/details/69791135

今天看到一个项目使用了BigInteger.setBit与BigInteger.testBit来实现权限控制,觉得很有趣,mark一下

首先,列出一下这两个方法的解释:

1.testBit方法的解释:

boolean java.math.BigInteger.testBit(int n)

Returns true if and only if the designated bit is set. (Computes ((this & (1<<n)) != 0).)

Parameters:
n index of bit to test.
Returns:
true if and only if the designated bit is set.
Throws:

ArithmeticException - n is negative.

意思就是将1左移n位,与this做&运算,其实就是判断当前数(要写成二进制)第n+1位上的数是不是为1,是的话返回true


2.setBit方法的解释

BigInteger java.math.BigInteger.setBit(int n)

Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set. (Computes (this | (1<<n)).)

Parameters:
n index of bit to set.
Returns:
this | (1<<n)
Throws:
ArithmeticException - n is negative.
意思就是将1左移n位,与this对象做|运算,这样的话,就会将this的二进制格式的第n+1位的数变为1.这样很明显就和上一个方法形成一对,
n可以作为某个功能编号,而角色可以使用setBit的方法设置编号,然后使用testBit来测试是不是含有n编号的功能。
如果每次有添加多个新的功能,那么就用这些功能编号依次给原来的角色编号执行setBit得到新的角色编号。

猜你喜欢

转载自blog.csdn.net/u011548068/article/details/69791135