要将长度为 65 或更长的二进制数转换为十进制/无论您必须编写如下方法:
public BigInteger FromBinaryString(string binary)
{
if (binary == null)
throw new ArgumentNullException();
if (!binary.All(c => c == '0' || c == '1'))
throw new InvalidOperationException();
BigInteger result = 0;
foreach (var c in binary)
{
result <<= 1;
result += (c - '0');
}
return result;
}
它使用System.Numerics.BigInteger
结构来保存大数字。然后您可以将其显式转换为decimal
(或字节数组)并将其存储在您的数据库中:
var bigInteger = FromBinaryString("100000000000000000000000000000000000000000000000000000000000000000");
// to decimal
var dec = (decimal)bigInteger;
// to byte array
var data = bigInteger.ToByteArray();
编辑:如果您在 NET 3.5 下,只需使用decimal
而不是BigInteger
(也将左移运算符替换为小数<<
的乘法运算符):*
public decimal FromBinaryString(string binary)
{
if (binary == null)
throw new ArgumentNullException();
if (!binary.All(c => c == '0' || c == '1'))
throw new InvalidOperationException();
decimal result = 0;
foreach (var c in binary)
{
result *= 2;
result += (c - '0');
}
return result;
}