Library tutorials & articles

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

Comments

  1. 11 Sep 2007 at 04:29
    I have just returned from an extended absence from this forum so I realize this is rather late.

    It looks good, the only thing I can spot is the line where you catch the Exception.  Not finding an extended numeral is expected (and common at that), so an Exception shouldn't be used to control the flow of code.

    Although I can't think of an easy way around it since they removed Enum.TryParse (2.0 and later I think).







  2. 24 May 2007 at 21:10
    Thanks for the Roman Numeral example! I made some equivalent functions in C# using Enum's static methods. This results in more concise versions of the two primary methods described in the article. They have been named a little bit differently to suit my tastes, but are the same methods in terms of the algorithm used. This code also uses the exact same RomanNumerals enum (which I haven't included in this snippet). Feel free to suggest further improvements, or to translate this back to VB.NET:

          
            private int ParseRomanNumeral(string numeral)
            {
                numeral = numeral.ToUpper();

                char[] characters = numeral.ToCharArray();
                int[] parseBuf = new int[numeral.Length];
                int result = 0;
                bool bSkip = false;
                for (int i = numeral.Length - 1; i >= 0; i--)
                {
                    if (bSkip)
                    {
                        bSkip = false; // Skip this digit because it is part of a 2-digit numeral
                        continue;
                    }
                    parseBuf[i] = (int)Enum.Parse(typeof(RomanNumerals), characters[i].ToString());
                    if (parseBuf[i] % 5 == 0 && i > 0)
                    {
                        string extended = characters[i-1].ToString() + characters[i].ToString();
                        try
                        {
                            parseBuf[i] = (int)Enum.Parse(typeof(RomanNumerals), extended);
                            bSkip = true;
                        }
                        catch(ArgumentException)
                        {
                            // Ignore this exception. It just means we didn't find an extended numeral
                        }
                    }
                }

                for (int i = 0; i < numeral.Length; i++)
                {
                    result += parseBuf[i];
                }
                return result;
            }

            private string ConvertToRomanNumeral(int num)
            {
                string sResult = "";

                sResult = Enum.GetName(typeof(RomanNumerals), num);
                if (sResult == null)
                {
                    string[] names = Enum.GetNames(typeof(RomanNumerals));
                    int[] vals = (int[])Enum.GetValues(typeof(RomanNumerals));
                    for (int i = names.Length - 1; i > 0; i--) // Don't process the 0th element, since it is 0 and results in bad math
                    {
                        int temp = num / vals[i];
                        num -= temp * vals[i];
                        for (int j = 0; j < temp; j++)
                        {
                            sResult += names[i];
                        }
                    }
                }

                return sResult;
            }





























































  3. 01 Jan 1999 at 00:00

    This thread is for discussions of Number Systems.

Leave a comment

Sign in or Join us (it's free).

Mitch Dusina Languages I know (from most comfortable with, to least comfortable with): VB.NET, C#, VB6, and C/C++ I'm 19 years old and pursuing a MS in Computer Science at the Colorado School of Mines. M...

Related discussion

Related podcasts

  • Christian Beauclair

    14 mai 2008 (�mission #0074) ::.Christian Beauclair: Stratégies de migration VB6 vers .NET Nous discutons avec Christian Beauclair des stratégies de migration VB6 vers .NET. Entre autres, nous discutons comment utiliser le "VB 6 Code Advisor" et le "Interop Forms Toolkit" pour ajouter la puiss...

We'd love to hear what you think! Submit ideas or give us feedback