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#
using System;
using System.Text;
class Program {
static void Main( string [] args)
{
string input = "56304" ;
int output = 0;
output = Convert.ToInt32(input, 16);
Console.WriteLine( "Integer number: " + output);
}
}
|
Output:
Integer number: 353028
Program 2:
C#
using System;
using System.Text;
namespace geeks {
class GFG {
static void Main( string [] args)
{
string input = "" ;
int output = 0;
try {
Console.Write( "Enter a hexadecimal number: " );
input = Console.ReadLine();
output = Convert.ToInt32(input, 16);
Console.WriteLine( "Integer number: " + output);
}
catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
|
Input:
598f
Output:
Enter a hexadecimal number:
Integer number: 22927
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
02 Jul, 2020
Like Article
Save Article