VBcoders Guest



Don't have an account yet? Register
 


Forgot Password?



Converts a number from one base to another, can handle bases 2-36.

by Dave Pipkin (1 Submission)
Category: Math/Dates
Compatability: VB 6.0
Difficulty: Unknown Difficulty
Originally Published: Mon 19th November 2001
Date Added: Mon 8th February 2021
Rating: (1 Votes)

Converts a number from one base to another, can handle bases 2-36.

Rate Converts a number from one base to another, can handle bases 2-36.



    On Error GoTo ErrHandle
    Dim conString As String
    Dim i As Integer
    Dim i2 As Integer
    Dim tmp As String
    Dim dig As String
    
    'Check for invalid bases
    If inBase < 2 Or inBase > 36 Or outBase < 2 Or outBase > 36 Then GoTo ErrHandle
    
    'Check for zero value
    If inNum = "0" Then GoTo ErrHandle
    
    'Check for negatives and fractions and remove
    If Left(inNum, 1) = "-" Then inNum = Mid(inNum, 2)
    If InStr(1, inNum, ".") > 0 Then inNum = Left(inNum, InStr(1, inNum, ".") - 1)
    
    'Capitalize
    inNum = UCase(inNum)
    
    'Check for hex prefixes
    If LCase(Left(inNum, 2)) = "0x" Or LCase(Left(inNum, 2)) = "&h" Then inNum = Right(inNum, Len(inNum) - 2)
    
    'String for all numbers up to base 36
    conString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
    'Convert to decimal
    If inBase <> 10 Then
        tmp = "0"
        For i = Len(inNum) To 1 Step -1
            dig = inBase ^ (Len(inNum) - i)
            tmp = Val(tmp) + Val(InStr(1, conString, Mid(inNum, i, 1)) - 1) * Val(dig)
        Next i
    Else
        tmp = inNum
    End If
    
    'Convert to outBase
    If outBase <> 10 Then
        If Val(tmp) < outBase Then
            convertNum = Mid(conString, Val(tmp) + 1, 1)
        Else
            convertNum = ""
            For i = 1 To 256
                If outBase ^ i > Val(tmp) Then
                    i2 = i
                    Exit For
                End If
            Next i
            For i = i2 To 1 Step -1
                dig = outBase ^ (i - 1)
                If Val(tmp) < Val(dig) Then
                    dig = "0"
                Else
                    dig = Int(Val(tmp) / Val(dig))
                    tmp = Val(tmp) - Val(dig) * outBase ^ (i - 1)
                End If
                convertNum = convertNum & Mid(conString, Val(dig) + 1, 1)
            Next i
        End If
    Else
        convertNum = tmp
    End If
    Exit Function
    
ErrHandle:
    convertNum = "0"
End Function

Download this snippet    Add to My Saved Code

Converts a number from one base to another, can handle bases 2-36. Comments

No comments have been posted about Converts a number from one base to another, can handle bases 2-36.. Why not be the first to post a comment about Converts a number from one base to another, can handle bases 2-36..

Post your comment

Subject:
Message:
0/1000 characters