简体   繁体   中英

Having trouble converting in binary to decimal for rather large numbers

I'm converting Binary numbers to decimal numbers fine until my number seems to surpass $2^64$ . It seems because the data type can't hold numbers larger than $2^64$ any insight? What happens is the number that is stored in my base_2 variable seems to not be able to surpass $2^64$ as it should when handling huge binary numbers but it overflows because the data type is too small and resets to 0...Any ideas how I can bypass this or fix this?

        //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();

An ulong can only hold values between 0 and 2**64; see UInt64.MaxValue .

Use a BigInteger when you want to deal with bigger values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM