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:
  1. Option Explicit
  2. Private Const NumStr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  3. Function Convert(ByVal Value As Long, ByVal Base As Long) As String
  4. Dim NumVal As Long
  5. Dim Answer As String
  6. Dim Negative As Boolean
  7.     If (Base < 2) Or (Base > 36) Then
  8.         Convert = "#BASE ERROR#"
  9.     Else
  10.         If Value < 0 Then
  11.             Negative = True
  12.             Value = -Value
  13.         Else
  14.             Negative = False
  15.         End If
  16.         Answer = ""
  17.         Do
  18.             If Value = 0 Then
  19.                 Exit Do
  20.             End If
  21.             NumVal = (Value Mod Base) + 1
  22.             Answer = Mid(NumStr, NumVal, 1) & Answer
  23.             Value = Value \ Base
  24.         Loop
  25.         If Negative Then
  26.             Answer = "-" & Answer
  27.         End If
  28.         Convert = Answer
  29.     End If
  30. End Function
  31. Function ConvertBack(ByVal Value As String, ByVal Base As Long) As Long
  32. Dim NumVal As Long
  33. Dim Answer As Long
  34. Dim Pos As Long
  35. Dim Negative As Boolean
  36.     If (Base < 2) Or (Base > 36) Then
  37.         ConvertBack = 0
  38.     Else
  39.         Answer = 0
  40.         If Left(Value, 1) = "-" Then
  41.             Pos = 2
  42.             Negative = True
  43.         Else
  44.             Negative = False
  45.             Pos = 1
  46.         End If
  47.         Do
  48.             If Pos > Len(Value) Then
  49.                 Exit Do
  50.             End If
  51.             NumVal = InStr(1, NumStr, Mid(Value, Pos, 1)) - 1
  52.             Answer = (Answer * Base) + NumVal
  53.             Pos = Pos + 1
  54.         Loop
  55.         If Negative Then
  56.             Answer = -Answer
  57.         End If
  58.         ConvertBack = Answer
  59.     End If
  60. End Function