Home »
C#.Net
Converting decimal, octal, hexadecimal string to integer using Convert.ToInt32() in C#
C# | convert decimal, octal or hexadecimal string to integer: Here, we are going to learn how to convert given decimal, octal or hexadecimal string to its equivalent integer number by using Convert.ToInt32() function in C#?
Submitted by IncludeHelp, on February 09, 2019
Convert.ToInt32() Method
Convert.ToInt32() is a predefined method in C#, which returns an integer value (in 32 bits) from given various types of values.
Here, we will go with some of the conversion...
Syntax:
Convert.ToInt32(input, base);
Here,
- input is the input string that may contain variable format's value like decimal/number value, octal value or hexadecimal value.
- base is the number system base like, 10 for decimal (which we do not need to write while calling the function), 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