Number Systems

Decimal To Any

    Converting from the Decimal system to others invloves some slightly complex math.  To fully understand this code you will need to understand how Mod functions.

Public Function DecimalToAny(ByVal Number As Long, ByVal Base As Short)_
 As String
Dim strNumberOutput As String
'These bounds are in place because they will hold the Long's
'largest possible value.
'An Int16 and String array are both used for readability. 
'You only need to use a string array
Dim intRemander(36) As Int16
Dim strRemander(36) As String
Dim IsNegative As Boolean
Dim i As Int16

'Roman Numerals
If Base = 0 Then
Return ToRomanNumeral(Number)
End If

'Supported Bases (1-9 A-Z)
If Base > 36 Or Base < 0 Then Throw New_
 Exception("Start Base can only be 0 through 36_
 (0-9, A-Z, or Roman Numerals)")

'Return 0 unless Unary (there is no number 0 in unary)
If Number = 0 And Base <> 1 Then
Return "0"
ElseIf Number = 0 And Base = 1 Then
Return ""
End If

'If needed, Adds the Negative sign after computation
If Number < 0 Then
IsNegative = True
Number *= -1
End If



'Special circumstances for Unary
If Base = 1 Then
Dim strUnary As String = ""

If IsNegative = True Then
strUnary = "-"
End If

'Think tick marks
For i = 0 To Number - 1
strUnary &= "1"
Next

Return strUnary
Exit Function
End If


'Count the remainders

Do Until Number = 0
intRemander(i) = Number Mod Base
strRemander(i) = intRemander(i).ToString

Number -= Number Mod Base
Number = (Number / Base)
i += 1
Loop


'Take off unused elements
ReDim Preserve intRemander(i - 1)
ReDim Preserve strRemander(i - 1)

'Converts > 9 to Text (10 = A)
For i = 0 To intRemander.GetUpperBound(0)
If Int(strRemander(i)) > 9 Then
strRemander(i) = Chr(strRemander(i) + 55)
End If
Next

'Concatinate the Remanders backwards
For i = intRemander.GetUpperBound(0) To 0 Step -1
strNumberOutput &= strRemander(i)
Next

'If needed, add that negative sign
If IsNegative = True Then strNumberOutput = "-" & strNumberOutput

Return strNumberOutput
End Function

You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“C++ : Where friends have access to your private members.” - Gavin Russell Baker