直接使用System.Numerics.BigInteger类(.NET 4.0+/Core 2.0+内置),需using System.Numerics;,支持字符串解析、整数转换、字节数组构造,具备完整算术、位运算与比较操作,不可变且无隐式转换,推荐TryParse输入和ToString输出。
直接用 System.Numerics.BigInteger 类,无需安装额外包(.NET Framework 4.0+ / .NET Core 2.0+ 均内置)。
先在文件顶部加引用:
using System.Numerics;然后就可以像普通数字一样声明和初始化:
BigInteger big = BigInteger.Parse("123456789012345678901234567890");
BigInteger big = (BigInteger)long.MaxValue + 1;
BigInteger big = new BigInteger(new byte[] { 0x01, 0x00 }); // 小端序,值为 1
加减乘除、取模、幂运算、位运算、比较符(==, !=, 等)全部可用,语法和 int 或 long 完全一致:
BigInteger a = BigInteger.Pow(2, 100); // 2 的 100 次方
BigInteger b = a * 3 + 7;bool isEven = (b & 1) == 0;BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b); // 内置 GCD 方法BigInteger 是不可变类型,每次运算都返回新实例;它不支持隐式转换,需显式转换或用 Parse/TryParse:
.ToString(),默认十进制;支持带格式器,如 big.ToString("X") 输出十六进制BigInteger.TryParse(...) 防异常,尤其来自用户输入或文件时123456789012345678901234567890BigInteger),必须靠 Parse 或构造函数基本上就这些。用起来很自然,关键就是记得引用 Numerics 命名空间,其他和普通数值类型几乎一样。