Base Conversions

VBScript Snippet

Convert a number from one base to another base

This routine will convert a string representation of a number from one base to another base e.g. 71 (base 10 ) converts to 107 (base 8).

VBScript has inbuilt functions hex() and oct(), but if you wanted to play around with other base numbers (2 to 20), try this. It can easily be adapted for larger base numbers.

Try it here. Note: the max. value is a long, 2.14 billion

eg 987654321              base 10 to base 16 converts to    3ADE68B1

Click to see versions in    vb     java

VBScript code

There are several ways to get the required information to vbscript - hard coded, arguments, text boxes (as above - view source code of this web page), or, as in the following, an input box (or boxes). I haven't included error handling for the input box.

Option Explicit
dim ans
ans = split(InputBox("enter a number to convert, base from, base to" & _
                                   vbnewline & "all separated by a single space" & _
                                   vbnewline & "e.g. 987654321 10 16")," ")

if ubound(ans) <> 2 then
    msgbox "data not per instructions - number base base"
    wscript.quit
end if

msgbox ans(0) & " (base " & ans(1) & ") " & " converts to " & _
              convert(ans(0),ans(1),ans(2)) & " (base " & ans(2) & ")"


Private Function convert(oldNum,base1,base2)
Dim temp,x,i,nextChar,convertedNumber,chars,validPos,index

chars = "0123456789ABCDEFGHIJ"                          '//add KLM.....XYZ etc to take base range to 36

if cint(base2) > len(chars) then                                       '//ERROR HANDLING
  convert = "error - invalid data detected"
  Exit Function
End If

For i = 1 To Len(oldNum)                                            '//ERROR HANDLING
  validPos = InStr(1, chars, Mid(oldNum, i, 1))
  If validPos = 0 Or validPos > cint(base1) Then
    convert = "error - invalid data detected"
    Exit Function
  End If
Next

On Error Resume Next                                                '//ERROR HANDLING
x = 1
For i = Len(oldNum) To 1 Step -1
  nextChar = Mid(oldNum, x, 1)
  x = x + 1
  temp = clng(temp) + clng(((InStr(1, chars, nextChar) - 1) * (base1 ^ (i - 1))))
Next
if err.number then
  convert = "number over 2.14 billion"
  exit function
end if
on error goto 0

x = 0
Do While temp > base2 ^ x
  x = x + 1
Loop

For i = 1 To x
  index = temp \ (base2 ^ (x - i))
  convertedNumber = convertedNumber & Mid(chars, index + 1, 1)
  temp = temp - index * (base2 ^ (x - i))
Next
convert = convertedNumber
End Function


back     top   main page    vb snippets page      java snippets page     vbscript snippets page   email    Page last modified