How do I convert number to base 10 from another base?

Category: System, viewed: 563 time(s).

In this example you'll see how to convert number from another base such as binary (base 2), octal (base 8) and hexadecimal (base 16) into the corresponding decimal (base 10) value.

The Convert.ToInt32(String value, int base) overloaded method take a string value representing a number and an integer representing the base of the number. This method then convert the numeric string into an integer and return this number as a base 10 value.

using System;

namespace Kodecsharp.Example.System
{
    public class NumberConverterDemo
    {
        public static void Main(string[] args)
        {
            string binary = "10";  // a binary string value
            string octal = "77";   // an octal string value
            string hexa = "9AFF";  // an hexadecimal string value.

            //
            // In the following lines we convert the number values represented
            // in the strings in specified base into an equivalent 32-bit 
            // signed integer value.
            //
            int val1 = Convert.ToInt32(binary, 2);
            int val2 = Convert.ToInt32(octal, 8);
            int val3 = Convert.ToInt32(hexa, 16);

            Console.Out.WriteLine("Binary " + binary + " = " + val1 + " decimal");
            Console.Out.WriteLine("Octal " + octal + "  = " + val2 + " decimal");
            Console.Out.WriteLine("Hexa " + hexa + " = " + val3 + " decimal");

            Console.ReadLine();
        }
    }
}

This class also have another method such as Convert.ToByte, Convert.ToDouble, Convert.ToInt64, etc. And below in a result produced by the example above.

Binary 10 = 2 decimal
Octal 77  = 63 decimal
Hexa 9AFF = 39679 decimal
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Statistics

Locations of visitors to this page