Option Explicit
Sub tester()
'testing sub - this code is NOT required to run the function - it only
'demonstrates the function in operation
Dim s As String
s = "Decimal number 255 in..." & vbCr & "Binary is " & Dec2Base(255, 2) & vbCr & _
"Octal is " & Dec2Base(255, 8) & vbCr & _
"Base 13 is " & Dec2Base(255, 13) & vbCr & _
"Hexadecimal is " & Dec2Base(255, 16)
MsgBox s
End Sub
Public Function Dec2Base(Num As Long, base As Long) As String
'converts a decimal number to the equivalent in the specified base
'(base 2 to base 16). Base needs to be specified as decimal ie
'8 for base 8, 16 for base 16, 2 for base 2 etc
Static Digits As Variant
Dim i As Long, alHolder() As Long, sTemp As String
If IsEmpty(Digits) Then _
Digits = VBA.Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
'check valid base:
If base > 16 Then Dec2Base = "Invalid base used": Exit Function
'fill holder array:
i = 0
Do
ReDim Preserve alHolder(0 To i)
alHolder(i) = Num Mod base
i = i + 1
Num = Num \ base
Loop While Num > 0
'build string result in base:
sTemp = ""
For i = i - 1 To 0 Step -1
sTemp = sTemp & Digits(alHolder(i))
Next i
'output:
Dec2Base = sTemp
End Function
|