C#: Convert a number in decimal to hexadecimal

C# Sharp For Loop: Exercise-55 with Solution

Write a program in C# Sharp to convert a decimal number to hexadecimal.

C# Sharp: Convert a number in decimal to hexadecimal

Sample Solution:-

C# Sharp Code:

using System;  // Importing necessary namespace

public class Exercise55  // Declaration of the Exercise55 class
    public static void Main()  // Main method, entry point of the program
        int decn, q, dn = 0, m, l;  // Declaration of variables
        int tmp;
        int s;
        Console.Write("Convert a number in decimal to hexadecimal:\n");

        Console.Write("Input  any Decimal number: ");
        decn = Convert.ToInt32(Console.ReadLine());  // Taking user input for a decimal number
        q = decn;

        // Converting decimal to hexadecimal
        for (l = q; l > 0; l = l / 16)
            tmp = l % 16;
            if (tmp < 10)
                tmp = tmp + 48;  // For digits less than 10, adding ASCII value of '0'
                tmp = tmp + 55;  // For digits greater than 9, adding ASCII value of 'A'

            dn = dn * 100 + tmp;  // Generating a number with two digits for each hexadecimal character

        Console.Write("\nThe equivalent Hexadecimal Number : ");
        // Reconstructing the hexadecimal number by extracting digits from the generated number
        for (m = dn; m > 0; m = m / 100)
            s = m % 100;  // Extracting two digits at a time
            Console.Write("{0}", (char)s);  // Printing the character equivalent of the hexadecimal number

        Console.Write("\n\n");  // Adding new lines for better readability

Sample Output:

Convert a number in decimal to hexadecimal:                                                                 
Input  any Decimal number: 1015                                                                             
The equivalent Hexadecimal Number : 3F7


Flowchart : Convert a number in decimal to hexadecimal

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a program in C# Sharp to convert an octal number into binary.
Next: Write a program in C# Sharp to Check Whether a Number can be Express as Sum of Two Prime Numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.