# Convert hexadecimal string to an integer number in C#

C# Convert hexadecimal string to an integer: Here, we will figure out how to change over a given string that contains a hexadecimal number in an integer number?

Given a hexadecimal string and we need to change over it into an integer number.

### Changing over from hexadecimal string to integer

Let guess you have a string “3039” which is a hexadecimal value of integer 12345, yet this value is in string organization, and you need to its integer (number) value.

To change over a hexadecimal string to an integer number – we use Convert.ToInt32() strategy.

### Syntax:

Convert.ToInt32(input_string, Input_base);

Here,

• input_string is the information containing a hexadecimal number in string position.
• input_base is the base of the information value – for a hexadecimal value, it will be 16.

### Example:

Input: "3039"
Function call:
Convert.ToInt32(input, 16);
Output:
12345

Input: "303a"
Function call:
Convert.ToInt32(input, 16);
Output:
12346

Input: "303ag" //not 'g' is not a valid hex digit
Function call:
Convert.ToInt32(input, 16);
Output:
Exception

### Code:

using System;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//hex number as string
string input = "3039";
int output = 0;
//converting to integer
output = Convert.ToInt32(input, 16);
//printing the value
Console.WriteLine("Integer number: " + output);

//hit ENTER to exit
}
}
}

Output:

Integer number: 12345

Example with Exception handling

Code:

using System;
using System.Text;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string input = "";
int output = 0;
try
{
//input string

//converting to integer
output = Convert.ToInt32(input, 16);

Console.WriteLine("Integer number: " + output);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

//hit ENTER to exit
}
}
}

Output:

First run with valid input:
Integer number: 12345

Second run with valid input: