You are on page 1of 2

C:\Documents and Settings\oosteep\My Documents\data\basic\Convert Base2Base\module1.

bas Tuesday, March 01, 2011 2:26 PM

1 Attribute VB_Name = "Module1"


2 Function Base2Base(InputNumber As String, InputBase As Integer, OutputBase As Integer) As String
3
4 Dim J, K, DecimalValue, X, MaxBase, InputNumberLength As Long ' Declare all variables
5 Dim NumericBaseData, OutputValue As String '
6
7 '
8 ' Initialize the symbols used for converting from one base to another. 0-F are standard for
9 ' bases between 2-16. G-z (lower case) just seemed like a logical sequence of characters
10 ' to use. The others are more or less random characters used as typical text. The double
11 ' quote (") has to be placed twice for Visual Basic to understand it asa single character
12 ' and not the end of the string.
13 NumericBaseData = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ,.;:'""!?()$%#/\@+-={}[]<>"
14
15 MaxBase = Len(NumericBaseData) ' Generically set the maximum base to the
16 ' length of NumericBaseData. If another
17 ' programmer changes the number of
18 ' characters in that variable, this line
19 ' will self adjust.
20
21 If (InputBase > MaxBase) Or (OutputBase > MaxBase) Then ' Check to make sure the user isn't trying
22 Base2Base = "N/A" ' to use a base that's larger than
23 Exit Function ' the set of characters.
24 End If
25
26 '*/ Convert InputNumber to Base 10 /*
27
28 InputNumberLength = Len(InputNumber) ' We need to know how long the input number is.
29 DecimalValue = 0 ' Set the initial decimal value of the number to 0.
30
31 For J = 1 To InputNumberLength ' Check each digit in the input number
32 For K = 1 To InputBase ' compare it to the symbol set.
33 If Mid(InputNumber, J, 1) = Mid(NumericBaseData, K, 1) Then
34 DecimalValue = DecimalValue + Int((K - 1) * (InputBase ^ (InputNumberLength - J)) + 0.5)
35 End If
36 Next K ' Using the formula (above) convert the input value to its decimal representation.
37 Next J
38
39 '*/ Convert the Base 10 value (DecimalValue) to the desired output base /*
40

-1-
C:\Documents and Settings\oosteep\My Documents\data\basic\Convert Base2Base\module1.bas Tuesday, March 01, 2011 2:26 PM

41 OutputValue = "" ' Set the output string to be blank.


42
43 ' As long as the decimal value is larger than 0 , then we've still got stuff to convert.
44 ' Find out which symbol needs to be tacked on to the output,
45 ' tack that symbol to the front of the output (we're converting from least significant
46 ' to most significant digit.)
47 ' Reduce the size of the decimal value by dividing by the output base value
48 While DecimalValue > 0
49 X = Int(((DecimalValue / OutputBase) - Int(DecimalValue / OutputBase)) * OutputBase + 1.5)
50 OutputValue = Mid(NumericBaseData, X, 1) + OutputValue
51 DecimalValue = Int(DecimalValue / OutputBase)
52 Wend
53
54 Base2Base = OutputValue ' Return the value
55
56 End Function
57

-2-

You might also like