Author : Rahul

Write a program to convert decimal number to hexadecimal number


Program

using System;

namespace ProgrammingQuestion
{
 class Program
 {
   static void Main(string[] args)
   {
     //Variable Declaration
     string decimalNumberVal, hexadecimalNumber="", hexadecimalDigit;
     int decimalNumber = 0, tempNumber, digit = 0;
     
     //User Input
     Console.Write("Enter Decimal Number:");
     decimalNumberVal = Console.ReadLine();
     decimalNumber = Convert.ToInt32(decimalNumberVal);
     
     //Decimal to Hexadecimal Logic
     tempNumber = decimalNumber;
     while (tempNumber > 0)
     {
       digit = tempNumber % 16;
       if (digit >= 0 && digit <= 9)
       {
         hexadecimalDigit = digit.ToString();
       }
       else
       {
         hexadecimalDigit = ((char)(digit + 55)).ToString();
       }
       hexadecimalNumber = hexadecimalNumber + hexadecimalDigit;
       tempNumber = tempNumber / 16;
     }
     
     //Reverse the string
     char[] hexadecimalNumberArray = hexadecimalNumber.ToCharArray();
     Array.Reverse(hexadecimalNumberArray);
     hexadecimalNumber = new string(hexadecimalNumberArray);
     
     //Print Result
     Console.WriteLine($"Hexadecimal Number: {hexadecimalNumber}");
     
     Console.Read();
   }
 }
}

Output

Enter Decimal Number:427
Hexadecimal Number: 1AB