This solution I provide myself appears to work - so simple too! But that's because it is a one-way conversion; the other libraries aim to be two-way conversion, back and forth between difference bases - but I don't need both ways.
Public Class BaseConverter
Public Shared Function ConvertToBase(num As Integer, nbase As Integer) As String
Dim retval = ""
Dim chars As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
' check if we can convert to another base
If (nbase chars.Length) Then
retval = ""
End If
Dim r As Integer
Dim newNumber As String = ""
' in r we have the offset of the char that was converted to the new base
While num >= nbase
r = num Mod nbase
newNumber = chars(r) & newNumber
'use: num = Convert.ToInt32(num / nbase)
'(if available on your system)
'otherwise:
num = num nbase
' notice the back slash - this is integer division, i.e the calculation only reports back the whole number of times that
' the divider will go into the number to be divided, e.g. 7 2 produces 3 (contrasted with 7 / 2 produces 3.5,
' float which would cause the compiler to fail the compile with a type mismatch)
End While
' the last number to convert
newNumber = chars(num) & newNumber
Return newNumber
End Function
End Class
I created the above code in Visual Basic based on the C# code in the following link:
CREDIT: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/5babf71f-4375-40aa-971a-21c1f0b9762b/
("convert from decimal(base-10) to alphanumeric(base-36)")
public String ConvertToBase(int num, int nbase)
{
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// check if we can convert to another base
if(nbase chars.Length)
return "";
int r;
String newNumber = "";
// in r we have the offset of the char that was converted to the new base
while(num >= nbase)
{
r = num % nbase;
newNumber = chars[r] + newNumber;
num = num / nbase;
}
// the last number to convert
newNumber = chars[num] + newNumber;
return newNumber;
}
@assylias I couldn't get devx.com/vb2themax/Tip/19316 to work - I got the wrong value back. Thanks though for the suggestion.
There is no evidence that it works. I adjusted some declarations and superficial structure of the code to get it to build successfully in Visual Studio Express 2010 Visual Basic. Then stepped through the code in the Visual Studio Express 2010 Visual Basic debugger, the code is hard to follow: variable names not obvious, no comments as to why it is doing what it is doing. From what I understood it was doing, it did not seem like it should be doing that to do the base conversion.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…