class Program
{
static void Main(string[] args)
{
//代表三个不同权限标识, 标识二进制中的第几位为1
var ints = new int[] { 1, 2, 4, 20, 80, 200 };
//存储所有权限的加权和。
//生成的数字的所组成的字符串长度和最大的标识有关和权限的个数无关,当最大标识为200时,长度为61。
BigInteger rights = new BigInteger(0);
foreach (var item in ints)
{
rights = BigInteger.Add(BigInteger.Pow(2, item), rights);
}
//下面判断是否具有权限21.
var isHaveRight = IsHaveRights(rights, 21);
//获得2417261343418899643214878 这个字符串的所有权限
var rightList = GetRightList(BigInteger.Parse("2417261343418899643214878"));
// 获得的值为1,2,3,4,10,11,13,15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,70,71,72,73,74,75,76,77,78,79,80
//显然若是直接存储上面的值,字符串就长很多了。
var stringJoins = String.Join(',', rightList);
}
private static List<int> GetRightList(BigInteger rights)
{
var bitCount = 8 * rights.GetByteCount();
List<int> list = new List<int>();
for (int i = 1; i <= bitCount; i++)
{
if (IsHaveRights(rights, i))
{
list.Add(i);
}
}
return list;
}
public static Boolean IsHaveRights(BigInteger rights, int right)
{
//左移运算,算出加权值
var rightPow = BigInteger.Pow(2, right);
//rights和加权值运算后判断和加权值比较是否相等
var hasRight = (rights & rightPow).CompareTo(rightPow) == 0;
return hasRight;
}
}
相关参考资料:
数据库权限优化,权限设计BigInteger https://blog.csdn.net/qq_39654446/article/details/78197688