Results 1 to 2 of 2

Thread: Number Base Conversion

  1. #1

    Thread Starter
    Hyperactive Member Troy Lundin's Avatar
    Join Date
    May 2006
    Posts
    489

    Number Base Conversion

    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.

    Code:
    Example: "AAAAAAAAAAAAAAAA" (36 -> 10) 2273903174270400214335488
    Reverse: 2273903174270400214335488 (10 -> 36) "AAAAAAAAAA9NGCU8"
    As you can see, the result gets messed up somewhere. I have tried other example posted across the net with similar results.

    Here is the function I am using.

    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
    Can anyone see what's wrong with it?
    Prefix has no suffix, but suffix has a prefix.

  2. #2

    Thread Starter
    Hyperactive Member Troy Lundin's Avatar
    Join Date
    May 2006
    Posts
    489

    Re: Number Base Conversion

    Okay, apparently converting a BigInteger to a string causes it to break?
    When I return the result to a string it is accurate. When I convert that string to a BigInteger I get a different number. I am going to look into this a bit more.
    Prefix has no suffix, but suffix has a prefix.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width