将数字从基数10转换为基数7数字c#

时间:2015-03-24 11:30:27

标签: c# .net int base

使用c#中的Convert.ToString方法,我只能将数字转换为基数为2,8,10或16.有没有办法将c / .net4或4.5转换/计算基数为10?

MSDN Convert.ToString Method (Int32, Int32)

2 个答案:

答案 0 :(得分:4)

您可以查看this blog,为此提供解决方案:

public static string DecimalToArbitrarySystem(long decimalNumber, int radix)
{
    const int BitsInLong = 64;
    const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if (radix < 2 || radix > Digits.Length)
        throw new ArgumentException("The radix must be >= 2 and <= " +
            Digits.Length.ToString());

    if (decimalNumber == 0)
        return "0";

    int index = BitsInLong - 1;
    long currentNumber = Math.Abs(decimalNumber);
    char[] charArray = new char[BitsInLong];

    while (currentNumber != 0)
    {
        int remainder = (int)(currentNumber % radix);
        charArray[index--] = Digits[remainder];
        currentNumber = currentNumber / radix;
    }

    string result = new String(charArray, index + 1, BitsInLong - index - 1);
    if (decimalNumber < 0)
    {
        result = "-" + result;
    }

    return result;
}

然后将其称为

Console.WriteLine("Base 7: " + DecimalToArbitrarySystem(number,  7));

答案 1 :(得分:0)

我试图将此解决方案转换为Vb.Net,使用所有C#到VB.Net的在线转换器,结果总是错误的。问题出在整数除法上。 (您可以尝试以5为基数计算320(C#= 2240是可以的。使用转换为VB.Net的结果始终是13340,这是错误的。)

这是VB.Net中的解决方案

Public Shared Function DecimalToArbitrarySystem(ByVal decimalNumber As Long, ByVal radix As Integer) As String
        Const BitsInLong As Integer = 64
        Const Digits As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        If radix < 2 OrElse radix > Digits.Length Then Throw New ArgumentException("The radix must be >= 2 and <= " & Digits.Length.ToString())
        If decimalNumber = 0 Then Return "0"
        Dim index As Integer = BitsInLong - 1
        Dim currentNumber As Long = Math.Abs(decimalNumber)
        Dim charArray As Char() = New Char(63) {}

        While currentNumber <> 0
            Dim remainder As Integer = CInt((currentNumber Mod radix))
            charArray(index) = Digits(remainder)
            index -= 1
            currentNumber = currentNumber \ radix
        End While

        Dim result As String = New String(charArray, index + 1, BitsInLong - index - 1)

        If decimalNumber < 0 Then
            result = "-" & result
        End If

        Return result
    End Function