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,

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output:
 

Integer number: 353028

Program 2: 
 

C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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();
    }
}
}

chevron_right


Input:

598f

Output:

Enter a hexadecimal number: 
Integer number: 22927



My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.