在将相当大的数字从二进制转换为十进制时遇到困难
本文关键字:十进制 遇到 转换 二进制 相当大 数字 | 更新日期: 2023-09-27 18:12:41
我正在将二进制数转换为十进制数,直到我的数字似乎超过$2^64$。这似乎是因为数据类型不能容纳大于2^64的数字,明白了吗?发生的事情是,存储在我的base_2变量的数字似乎不能超过$2^64$,因为它应该处理巨大的二进制数,但它溢出,因为数据类型太小,重置为0…有什么办法能让我绕过或解决这个问题吗?
//Vector to store the Binary # that user has input
List<ulong> binaryVector = new List<ulong>();
//Vector to store the Decimal Vector I will output
List<string> decimalVector = new List<string>();
//Variable to store the input
string input = "";
//Variables to do conversions
ulong base2 = 1;
ulong decimalOutput = 0;
Console.WriteLine("2^64=" + Math.Pow(2.00,64));
//Prompt User
Console.WriteLine("Enter the Binary Number you would like to convert to decimal: ");
input = Console.ReadLine();
//Store the user input in a vector
for(int i = 0; i < input.Length; i++)
{
//If we find a 0, store it in the appropriate vector, otherwise we found a 1..
if (input[i].Equals('0'))
{
binaryVector.Add(0);
}
else
{
binaryVector.Add(1);
}
}
//Reverse the vector
binaryVector.Reverse();
//Convert the Binary # to Decimal
for(int i = 0; i < binaryVector.Count; i++)
{
//0101 For Example: 0 + (0*1) = 0 Thus: 0 is out current Decimal
//While our base2 variable is now a multiple of 2 (1 * 2 = 2)..
decimalOutput = decimalOutput + (binaryVector[i] * base2);
base2 = base2 * 2;
Console.WriteLine("'nTest base2 Output Position[" + i + "]::" + base2);
}
//Convert Decimal Output to String
string tempString = decimalOutput.ToString();
一个ulong
只能保存0到2**64之间的值;看到UInt64.MaxValue。
当你想处理更大的值时使用BigInteger