With Convert.ToString Method in c# i can only convert numbers to base 2, 8, 10, or 16. is there a way to Convert/calculate base 10 number to base 7 with c# .net4 or 4.5?
You can check this blog which gives a solution for this:
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;
}
And then call it like
Console.WriteLine("Base 7: " + DecimalToArbitrarySystem(number, 7));
I tryed to convert this solution to Vb.Net and the result was always wrong using all the C# to VB.Net online converter. The problem was with the integer division. (You can try to calculate 320 in radix 5 (C#=2240 is OK. Using the conversion to VB.Net the result is always 13340 witch is wrong).
Here is the solution in 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
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.