将非十进制数转换为另一个非十进制数

Hao*_*est 0 algorithm base-conversion

这不是很多工作,但我知道将非十进制转换为另一个非小数的唯一方法是先将数字转换为十进制,然后再采取第二步将其转换为新的基数.例如,要将456(在基数7中)转换为567(在基数8中),我会计算456的十进制值,然后将该值转换为基数8 ...

有没有更好的方法直接从7到8?或任何其他基地的任何基础?

这就是我所拥有的:


   //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;
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

您并没有真正转换为基数10.您将其转换为数字数据类型而不是字符串表示形式.如果有的话,你将它转换为二进制:)它值得区分"一个整数"(它本身没有基础)和"整数的文本表示"(确实如此).

这似乎是一种明智的方式,IMO.但是,您的转换例程肯定不是特别有效.我会将你的代码分离到ParseFormat方法,然后Convert方法可以是这样的:

public static string Convert(string text, int sourceBase, int targetBase)
{
    int number = Parse(text, sourceBase);
    return Format(number, targetBase);
}
Run Code Online (Sandbox Code Playgroud)

(当然,你可以使用a string表示不同的基础.如果你真的需要那种灵活性,我会想要创建一个新的类来表示"数字表示".那个类应该是在一个拥有Parse,FormatConvert在里面.)