views:

204

answers:

1

Not that it's a lot of work, but the only way I know to convert a non-decimal to another non-decimal is by converting the number to decimal first, then take a second step to convert it to a new base. For example, to convert 456 (in base 7) to 567 (in base 8), I would calculate the decimal value of 456, then convert that value into base 8...

Is there a better way to go directly from 7 to 8? or any base to any other base for that matter?

Here's what I have:


   //source_lang and target_lang are just the numeric symbols, they would be "0123456789" if they were decimal, and "0123456789abcdef" if hex.
   private string translate(string num, string source_lang, string target_lang)
    {
        int b10 = 0;
        string rv = "";
        for (int i=num.Length-1; i>=0; i--){
            b10 += source_lang.IndexOf( num[i] ) * ((int)Math.Pow(source_lang.Length, num.Length -1 - i));
        }
        while (b10 > 0) {
            rv = target_lang[b10 % target_lang.Length] + rv;
            b10 /= target_lang.Length;
        }
        return rv;
    }
+8  A: 

You're not really converting into base 10. You're converting it into a numeric data type instead of a string representation. If anything, you're converting it into binary :) It's worth distinguishing between "an integer" (which doesn't intrinsically have a base) and "the textual representation of an integer" (which does).

That seems like a sensible way to go, IMO. However, your conversion routines certainly aren't particularly efficient. I would separate out your code into Parse and Format methods, then the Convert method can be something like:

public static string Convert(string text, int sourceBase, int targetBase)
{
    int number = Parse(text, sourceBase);
    return Format(number, targetBase);
}

(You can use a string to represent the different bases if you want, of course. If you really need that sort of flexibility though, I'd be tempted to create a new class to represent a "numeric representation". That class should probably be the one to have Parse, Format and Convert in it.)

Jon Skeet