Advanced Base Converter

By | 2002-06-01

Updated code! This function converts numbers into any base, and any base into decimal! Works frek-in’ awesome!

Original Author: Feuchtersoft

Assumptions

Not all bases will work; there are not enough characters to be able to do every base. An error will occur when this happens.

Returns

‘ The two functions given are reversible. For example:
ConvertToBase(45, 16) = “2D”
ConvertFromBase(“2D”, 16) = 45

Side Effects

Will not (yet) deal with negative numbers, and rounds all numbers that are decimal.

Code

Function ConvertToBase(DecNumber As Double, NewBase As Integer) As String
Dim ModBase As Double
Do
ModBase = CDbl(DecNumber - (Int(DecNumber / NewBase)) * NewBase)
DecNumber = Int(DecNumber / NewBase)
If ModBase > 9 Then ModBase = ModBase + 7
ConvertToBase = Chr(ModBase + 48) & ConvertToBase
Loop Until DecNumber = 0
End Function
Function ConvertFromBase(BaseNumber As String, OldBase As Integer) As Double
Dim i As Integer, LetterVal As Integer
On Error Resume Next
For i = 1 To Len(BaseNumber)
LetterVal = Asc(Mid(BaseNumber, Len(BaseNumber) - i + 1, 1)) - 48
If LetterVal > 9 Then LetterVal = LetterVal - 7
If LetterVal > OldBase Then GoTo InvalidNumber
ConvertFromBase = ConvertFromBase + (OldBase ^ (i - 1)) * LetterVal
Next i
InvalidNumber:
End Function

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.