Skip to content
Related Articles

Related Articles

Improve Article
C# Program for Converting Hexadecimal String to Integer
  • Last Updated : 02 Jul, 2020

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,

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

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#




// 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#




// 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



My Personal Notes arrow_drop_up
Recommended Articles
Page :