找不到System.Numerics命名空间的解决方案
使用NuGet搜System.Numerics,找到带Runtime这个项目安装。目前VS没有自带这个运行库。
BigInteger转二进制字符串
出处:https://stackoverflow.com/questions/33611930/convert-biginteger-binary-to-biginteger-number
// 使用一个工具类包裹转换函数
public static class Util
{
public static string ToBinaryString(this BigInteger bigint)
{
var bytes = bigint.ToByteArray();
var idx = bytes.Length - 1;
// Create a StringBuilder having appropriate capacity.
var base2 = new StringBuilder(bytes.Length * 8);
// Convert first byte to binary.
var binary = Convert.ToString(bytes[idx], 2);
// Ensure leading zero exists if value is positive.
if (binary[0] != '0' && bigint.Sign == 1)
{
base2.Append('0');
}
base2.Append(binary);
for (idx--; idx >= 0; idx--)
{
base2.Append(Convert.ToString(bytes[idx], 2).PadLeft(8, '0'));
}
return base2.ToString();
}
}
二进制字符串转BigInteger
出处:https://stackoverflow.com/questions/56333862/faster-way-to-convert-large-binary-string-to-biginteger
private BigInteger BinaryStringToBigInteger(string b)
{
BigInteger Decimalvalue = 0;
foreach (char c in b)
{
Decimalvalue <<= 1;
Decimalvalue += c == '1' ? 1 : 0;
}
return Decimalvalue;
}