Hi all,
It's been a while since I last posted anything in the code bank, but today I made to useful functions that I thought I would share with you guys.
The functions convert base 10 integers to any base you like, with any alphabet you like. The second function can also convert base n numbers of any alphabet back to a base 10 integer. In the second function it would probably be more efficient to use some type of dictionary or lookup instead of index of.
vb.net Code:
Function ConvertToBase(ByVal Base As Integer, ByVal alphabet As String, ByVal number As Integer) As String
Dim modv As Integer = number
Dim div As Integer = number
Dim st As New System.Text.StringBuilder()
While div <> 0
modv = div Mod Base
div = div \ Base
st.Append(alphabet(modv))
End While
Dim rev As Char() = st.ToString.ToCharArray
Array.Reverse(rev)
Return rev
End Function
Function ConvertFromBase(ByVal Base As Integer, ByVal alphabet As String, ByVal number As String) As Integer
Dim acc As Integer
Dim rev As Char() = number
Array.Reverse(rev)
For i = 0 To number.Length - 1
acc += (alphabet.IndexOf(rev(i))) * (Base ^ i)
Next
Return acc
End Function
And here is an example usage
vb.net Code:
RichTextBox1.AppendText(ConvertToBase(16, "0123456789ABCDEF", 34623) & vbNewLine)
RichTextBox1.AppendText(CStr(ConvertFromBase(16, "0123456789ABCDEF", "873F")))
Output:
You could probably create a third function that can convert base n for any arbitrary alphabet to another base n with an arbitrary alphabet. I can think of many interesting things these functions could be used for.