Search code examples
c#binarytype-conversiondecimalradix

C# Converting From Base to Decimal went Crazy


So I just got an idea to convert any base to Decimal (Base 10):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoloLearn
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What is the number you want to convert?");
            string num = Console.ReadLine();
            Console.WriteLine("In what base is this number?");
            int mathBase = int.Parse(Console.ReadLine());
            double output = 0;
            int j = 0;
            char[] nums = num.ToCharArray();
            for(int i=num.Length - 1; i>=0; i--) {
               output = output + Math.Pow(mathBase,i) * nums[j] * 1;
               Console.WriteLine("i: " + i +", j:" + j + ", nums[j]: " + nums[j] + ", output: " + output + ", mathBase: " + mathBase + ", " + Math.Pow(mathBase,i) + ".");
               j++; 
            }
            Console.WriteLine("The number " + num + " in base 10 (Decimal) is " + output + ".");
            Console.ReadLine();
        }
    }
}

So I started with binary (num = 100, mathBase = 2) but the answers went crazy. That's why I added this code to see what the heck happens:

Console.WriteLine("i: " + i +", j:" + j + ", nums[j]: " + nums[j] + ", output: " + output + ", mathBase: " + mathBase + ", " + Math.Pow(mathBase,i) + "."); 
j++;  

And well, all the variables were right:

This is the output and code

So yeah, I really dont know what happens, because all the calculations seems right (Math.Pow(mathBase,i) = 2^2 = 4, as shown but, 4 * nums[j] = 4 * 1 = 196 ? Please if anyone knows What the heck happens, let me know!


Solution

  • Your problem is that nums is a char[]. Thus nums[j] is a char. Now the problem you are seeing is that a char can be implicitly converted to a number but not in the way you are wanting - it is using the ascii value of it so 1 is ascii value 49 and 0 is ascii value 48. And that's when the maths goes all wrong.

    What you need to do is convert your input sting into an array of ints, not an array of characters. Some example code that might do this is:

    int[] nums = num.Select(x=>x-'0').ToArray();
    

    What this does is makes use of the fact that the characters 0-9 are ascii 48-57 and that if you take ascii 0 (48) off each of these you will get 0-9. It also takes advantage of the fact that a string is also a IEnumerable<char> and thus can be easily LINQed.

    With this modification your program should work as expected.