Skip to content
Related Articles

Related Articles

Java Program For Decimal to Hexadecimal Conversion
  • Last Updated : 09 Mar, 2021

Given a decimal number N, convert N into an equivalent hexadecimal number i.e convert the number with base value 10 to base value 16. The decimal number system uses 10 digits 0-9 and the Hexadecimal number system uses 0-9, A-F to represent any numeric value.

Examples: 

Input : 10
Output: A

Input : 2545
Output: 9F1

Approach:

  1. Store the remainder when the number is divided by 16 in an array.
  2. Divide the number by 16 now
  3. Repeat the above two steps until the number is not equal to 0.
  4. Print the array in reverse order now.

Implementation:

Example



Java




// Java program to convert Decimal Number
// to Hexadecimal Number
  
// Importing input output classes
import java.io.*;
  
// Main class
public class GFG {
  
    // Method 1
    // To convert decimal to hexadecimal
    static void decTohex(int n)
    {
        // Creating an array to store octal number
        int[] hexNum = new int[100];
  
        // counter for hexadecimal number array
        int i = 0;
        while (n != 0) {
  
            // Storing remainder in hexadecimal array
            hexNum[i] = n % 16;
            n = n / 16;
            i++;
        }
  
        // Printing hexadecimal number array
        // in the reverse order
        for (int j = i - 1; j >= 0; j--) {
            if (hexNum[j] > 9)
                System.out.print((char)(55 + hexNum[j]));
            else
                System.out.print(hexNum[j]);
        }
    }
  
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input decimal number
        // to be converted into hexadecimal number
        int n = 2545;
  
        // Calling the above Method1 over number 'n'
        // to convert this decimal into hexadecimal number
        decTohex(n);
    }
}
Output
9F1

Time Complexity: O(log N) 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :