无法将二进制转换为十进制数字

时间:2015-09-13 02:07:16

标签: c# binary bit-manipulation binary-data bits

我将二进制数转换为十进制数,直到我的数字似乎超过$ 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();

1 个答案:

答案 0 :(得分:2)

ulong只能保存0到2之间的值** 64;见UInt64.MaxValue

如果您想处理更大的值,请使用BigInteger