Click here to Skip to main content
15,499,155 members
Articles / Programming Languages / C#
Posted 27 May 2005


34 bookmarked

Conversion of Decimal to any Base (Binary, Octal or Hexa) and vice-versa (C#)

Rate me:
Please Sign up or sign in to vote.
3.35/5 (23 votes)
27 May 2005CPOL2 min read
Generic functions written in C# to convert a binary,octal or a hexa-decimal to a decimal number and vice-versa.


C# conversion functions are very powerful. The Convert class has many methods that perform typical conversion of a string to integer, and other data types. One of the functions ToInt64() not only converts a given value to a 64-bit integer but also returns the number to the specified base.


The above function converts a decimal number to hexadecimal number. This is most useful in situations where you write programs for arithmetic calculations. I thought of writing my own function that does this kind of conversion. I created two functions, DecimalToBase which converts any decimal number to a binary, octal or hexadecimal number and BaseToDecimal which converts any binary, octal or hexadecimal number to the corresponding decimal number.

The most interesting part is that both the functions are generic in nature. In the DecimalToBase function, I had to write the algorithm that can perform the conversion of a decimal to binary, octal or hexadecimal. I had to write the code for all of these conversions within a single function, still keeping my code reduced to handle all sorts of values. C#’s type-safe nature prevents us from doing some easier character-int conversions and we just can’t surpass them, as it would produce adverse results. Same is the case with the BaseToDecimal function.

A sample application to test the conversion functions

  • Create a sample Windows application in Visual Studio. NET.
  • In the form:
    1. Add three label controls named label1, label2, and label3.
    2. Add three text box controls named textBox1, textBox2, and textBox3.
    3. Place a button control named button1 and set its Text property to “To Base”.
    4. Place another button control named button2 and set its Text property to “To Base”.
  • Write the following declarations as data members of the form class:
    const int base10 = 10;
    char[] cHexa = new char[]{'A','B','C','D','E','F'};
    int[] iHexaNumeric = new int[] {10,11,12,13,14,15};
    int[] iHexaIndices = new int[] {0,1,2,3,4,5};
    const int asciiDiff = 48;
  • Include the functions as member methods in the form class module.

    This function takes two arguments; the integer value to be converted and the base value (2, 8, or 16) to which the number is converted to:

    string DecimalToBase(int iDec, int numbase)
        string strBin = "";
        int[] result = new int[32];
        int MaxBit = 32;
        for(; iDec > 0; iDec/=numbase)
            int rem = iDec % numbase;
            result[--MaxBit] = rem;
        for (int i=0;i<result.Length;i++)
              if ((int) result.GetValue(i) >= base10)
                strBin += cHexa[(int)result.GetValue(i)%base10];
                strBin += result.GetValue(i);
        strBin = strBin.TrimStart(new char[] {'0'});
        return strBin;

    This function takes two arguments; a string value representing the binary, octal, or hexadecimal value and the corresponding integer base value respective to the first argument. For instance, if you pass the first argument value "1101", then the second argument should take the value "2".

    int BaseToDecimal(string sBase, int numbase)
        int dec = 0;
        int b;
        int iProduct=1;
        string sHexa = "";
        if (numbase > base10)
        for (int i=0;i<cHexa.Length;i++)
            sHexa += cHexa.GetValue(i).ToString();
        for(int i=sBase.Length-1; i>=0; i--,iProduct *= numbase)
            string sValue = sBase[i].ToString();
            if (sValue.IndexOfAny(cHexa) >=0)
                b= (int) sBase[i] - asciiDiff;
            dec += (b * iProduct);
        return dec; 
  • Write the code in the click event of the buttons as follows:

    On clicking the first button, you can convert a decimal number to any base you select in the ComboBox.

    private void button1_Click(object sender, System.EventArgs e)
        textBox3.Text = DecimalToBase(Int32.Parse(textBox1.Text), 

    On clicking the second button, you can convert the base number you have selected in the ComboBox (binary, octal, or hexadecimal) to a decimal number.

    private void button2_Click(object sender, System.EventArgs e)
        textBox3.Text = BaseToDecimal(textBox1.Text, 
  • Save the project. Build the solution.
  • Output is as shown below:

Sample Output #1:

Sample Output #2:

Sample Output #3:

Sample Output #4:


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Founder BB Systems CIT-GPNP
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

GeneralMy vote of 5 Pin
Gun Gun Febrianza25-Sep-13 4:47
Member Gun Gun Febrianza25-Sep-13 4:47 
QuestionHere is a more general 30-minute semi-glitchy job that will convert between non-integer bases. Pin
Kerdekz28-Apr-12 17:18
MemberKerdekz28-Apr-12 17:18 
QuestionCan a Fractional number be converted to Binary ? Pin
Ganesamoorthy.S19-Jan-12 0:26
MemberGanesamoorthy.S19-Jan-12 0:26 
AnswerRe: Can a Fractional number be converted to Binary ? Pin
Kerdekz28-Apr-12 17:29
MemberKerdekz28-Apr-12 17:29 
Generalworks great, thanks! Pin
spyhunter9994-Sep-11 3:09
Memberspyhunter9994-Sep-11 3:09 
GeneralMy vote of 4 Pin
shelby6716-Jun-11 20:29
Membershelby6716-Jun-11 20:29 
GeneralMy New Version - Using bitwise-AND operator [modified] Pin
dciobanu2007@gmail.com23-Apr-09 11:53
Memberdciobanu2007@gmail.com23-Apr-09 11:53 
GeneralBig numbers problem Pin
kavy77711-Feb-09 23:42
Memberkavy77711-Feb-09 23:42 
GeneralMy Versions Pin
kender_216-Jul-07 9:01
Memberkender_216-Jul-07 9:01 
GeneralRe: My Versions Pin
Shabbazz7-Aug-07 2:05
professionalShabbazz7-Aug-07 2:05 
GeneralRe: My Versions Pin
blackjack215017-Oct-07 21:49
Memberblackjack215017-Oct-07 21:49 
GeneralRe: My Versions Pin
LightningSt0rm9-Nov-07 12:58
MemberLightningSt0rm9-Nov-07 12:58 
GeneralRe: My Versions Pin
LightningSt0rm9-Nov-07 13:24
MemberLightningSt0rm9-Nov-07 13:24 
GeneralRe: My Versions Pin
Elad Moshe16-Aug-09 23:11
MemberElad Moshe16-Aug-09 23:11 
GeneralThanks :-D Pin
jackmandile22-Nov-06 9:52
Memberjackmandile22-Nov-06 9:52 
GeneralWonderful Pin
Fahad Azeem24-Nov-05 22:28
MemberFahad Azeem24-Nov-05 22:28 
GeneralImprovement Pin
Nigel Savidge15-Sep-05 5:52
MemberNigel Savidge15-Sep-05 5:52 
GeneralRe: Improvement [modified] Pin
lemueladane12-May-08 22:56
Memberlemueladane12-May-08 22:56 
GeneralRe: Improvement Pin
Nigel Savidge14-May-08 6:03
MemberNigel Savidge14-May-08 6:03 
GeneralRe: Improvement [modified] Pin
lemueladane14-May-08 5:05
Memberlemueladane14-May-08 5:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.