Converting a decimal, octal, hexadecimal string to an integer using Convert.ToInt32() in C#

C# convert a decimal, octal or hexadecimal string to an integer: Here, we will figure out how to change over given decimal, octal or hexadecimal string to its identical integer number by utilizing Convert.ToInt32() work in C#?

Convert.ToInt32() Method

Convert.ToInt32() is a predefined strategy in C#, which restores an integer value (in 32 bits) from given different kinds of values.

Here, we will go with a portion of the changeā€¦

Syntax:

Convert.ToInt32(input, base); 

Here,

  • input is the information string that may contain variable arrangement’s value like decimal/number value, octal value or hexadecimal value.
  • the base is the number framework base like, 10 for decimal (which we don’t have to compose while calling the capacity), 8 for octal and 16 for the hexadecimal value.

Code:

using System;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "";
            int num = 0;
            try
            {
                input = "12345"; //value is a decimal formatted number
                num = Convert.ToInt32(input); //base is an optional if string contains decimal value 
                Console.WriteLine("num (decimal string to integer) :" + num);
                //we can also provide the base of the input - it is decimal value 
                //so, 10 can be used as base 
                num = Convert.ToInt32(input, 10);
                Console.WriteLine("num (decimal string to integer) :" + num);

                //convert octal string to integer
                input = "30071";
                num = Convert.ToInt32(input, 8);
                Console.WriteLine("num (octal string to integer) :" + num);

                //convert hex string to integer
                input = "3039ACFE";
                num = Convert.ToInt32(input, 16);
                Console.WriteLine("num (hex string to integer) :" + num);                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

num (decimal string to integer) :12345
num (decimal string to integer) :12345
num (octal string to integer) :12345
num (hex string to integer) :809086206

Leave a Comment

error: Alert: Content is protected!!