Author : Rahul

Write a program to convert hexadecimal number to decimal number


Program

using System;

namespace ProgrammingQuestion
{
 class Program
 {
   static void Main(string[] args)
   {
     //Variable Declaration
     string hexadecimalNumberVal, hexadecimalNumber;
     int decimalNumber = 0, digit = 0, power = 0;

     //User Input
     Console.Write("Enter Hexadecimal Number:");
     hexadecimalNumberVal = Console.ReadLine();
     
     //Hexadecimal to Decimal Logic
     hexadecimalNumber = hexadecimalNumberVal.ToUpper();
     for (int i = hexadecimalNumber.Length - 1; i >= 0; i--)
     {
       if (hexadecimalNumber[i] >= '0' && hexadecimalNumber[i] <= '9')
       {
         digit = hexadecimalNumber[i] - 48;
       }
       else if (hexadecimalNumber[i] >= 'A' && hexadecimalNumber[i] <= 'F')
       {
         digit = hexadecimalNumber[i] - 55;
       }
       decimalNumber = decimalNumber + digit * (int)Math.Pow(16, power);
       power++;
     }
     
     //Print Result
     Console.WriteLine($"Decimal Number: {decimalNumber}");
     
     Console.Read();
   }
 }
}

Output

Enter Hexadecimal Number:1ab
Decimal Number: 427