I have been using this code for a long time now and it has always been accurate. I recently tried to convert a large string from one base to another and some weird stuff happens.
When I convert from base 36 to base 10, the result is accurate.
When I convert the result back to base 36, it becomes inaccurate.
As you can see, the result gets messed up somewhere. I have tried other example posted across the net with similar results.Code:Example: "AAAAAAAAAAAAAAAA" (36 -> 10) 2273903174270400214335488
Reverse: 2273903174270400214335488 (10 -> 36) "AAAAAAAAAA9NGCU8"
Here is the function I am using.
Can anyone see what's wrong with it?Code:Public Function ConvertBase(ByVal ValueToConvert As String, ByVal FromBase As Int32, ByVal ToBase As Int32) As String
Dim s As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim fromValue As New System.Text.StringBuilder(ValueToConvert.ToString)
Dim power As Int32 = 0
Dim result As BigInteger = 0
While fromValue.Length > 0
Dim index As Integer = s.IndexOf(fromValue(fromValue.Length - 1))
If index < 0 Then Throw New FormatException("ValueToConvert contains an unsupported character.")
If index > FromBase Then Throw New FormatException("ValueToConvert contains an invalid character for FromBase.")
result += BigInteger.Multiply(index, BigInteger.Pow(FromBase, power))
If result < 0 Then Throw New OverflowException()
fromValue.Length -= 1
power += 1
End While
If ToBase = 10 Then Return result.ToString
Dim ret As New System.Text.StringBuilder
While result > 0
Dim index As Integer = CInt(result Mod ToBase)
ret.Insert(0, s(index))
result = result / ToBase
End While
Return ret.ToString
End Function
