Open In App

C# Program for Converting Hexadecimal String to Integer

Given an hexadecimal number as input, we need to write a program to convert the given hexadecimal number into equivalent integer. To convert an hexadecimal string to integer, we have to use Convert.ToInt32() function to convert the values.

Syntax: 



Convert.ToInt32(input_string, Input_base);

Here,

Examples:



Input : 56304
Output : 353028

Input : 598f
Output : 22927

If we input wrong value for eg. 672g, it shows error: Enter a hexadecimal number: System.FormatException: Additional unparsable characters are at the end of the string.

If we input number greater than 8 digit e.g. 746465789, it shows error: Enter a hexadecimal number: System.OverflowException: Arithmetic operation resulted in an overflow.

Program 1: 
 




// C# program to convert array 
// of hexadecimal strings to integers
using System;
using System.Text;
  
class Program {
    
    static void Main(string[] args)
    {
        // hexadecimal number as string
        string input = "56304";
        int output = 0;
        
        // converting to integer
        output = Convert.ToInt32(input, 16);
        
        // to print  the value
        Console.WriteLine("Integer number: " + output);
    }
}

Output:
 

Integer number: 353028

Program 2: 
 




// C# program to convert array 
// of hexadecimal strings
// to integers
using System;
using System.Text;
  
namespace geeks {
    
class GFG {
    
    static void Main(string[] args)
    {
        string input = "";
        int output = 0;
        try {
            
            // input string
            Console.Write("Enter a hexadecimal number: ");
            input = Console.ReadLine();
  
            // converting to integer
            output = Convert.ToInt32(input, 16);
  
            Console.WriteLine("Integer number: " + output);
        }
        catch (Exception ex) {
            Console.WriteLine(ex.ToString());
        }
  
        // hit ENTER to exit
        Console.ReadLine();
    }
}
}

Input:

598f

Output:

Enter a hexadecimal number: 
Integer number: 22927

Article Tags :