Hi All,
I was looking at the problem of developing a routine to convert between a
number of different bases - 2, 4, 8, 10, 16 etc.
I came up with the following which seems to work fine, can anyone come up with a better way?![]()
VB Code:
Option Explicit Private Const NumStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" Function Convert(ByVal Value As Long, ByVal Base As Long) As String Dim NumVal As Long Dim Answer As String Dim Negative As Boolean If (Base < 2) Or (Base > 36) Then Convert = "#BASE ERROR#" Else If Value < 0 Then Negative = True Value = -Value Else Negative = False End If Answer = "" Do If Value = 0 Then Exit Do End If NumVal = (Value Mod Base) + 1 Answer = Mid(NumStr, NumVal, 1) & Answer Value = Value \ Base Loop If Negative Then Answer = "-" & Answer End If Convert = Answer End If End Function Function ConvertBack(ByVal Value As String, ByVal Base As Long) As Long Dim NumVal As Long Dim Answer As Long Dim Pos As Long Dim Negative As Boolean If (Base < 2) Or (Base > 36) Then ConvertBack = 0 Else Answer = 0 If Left(Value, 1) = "-" Then Pos = 2 Negative = True Else Negative = False Pos = 1 End If Do If Pos > Len(Value) Then Exit Do End If NumVal = InStr(1, NumStr, Mid(Value, Pos, 1)) - 1 Answer = (Answer * Base) + NumVal Pos = Pos + 1 Loop If Negative Then Answer = -Answer End If ConvertBack = Answer End If End Function





Reply With Quote