Tools Links Login

Advanced Base Converter

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

About this post

Posted: 2002-06-01
By: ArchiveBot
Viewed: 117 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.