Java Program for decimal to hexadecimal conversion

0
41
Java Program for decimal to hexadecimal conversion

Lets first understand what Hexadecimal conversion is. Hexadecimal numbers use 16 values to represent a number. Numbers from 0-9 are expressed by digits 0-9 and 10-15 are represented by characters from A – F.

The Hexadecimal is similar to we use in Mathematics here is the algorithm explaining decimal to hexadecimal conversion

Algorithm:

  1. Store the remainder when the number is divided by 16 in a temporary variable temp. If temp is less than 10, insert (48 + temp) in a character array otherwise if temp is greater than or equals to 10, insert (55 + temp) in the character 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.

Java Program for decimal to hexadecimal conversion

import java.io.*; 
  
class GFG  
{ 
    // function to convert decimal to hexadecimal 
    static void decToHexa(int n) 
    {    
        // char array to store hexadecimal number 
        char[] hexaDeciNum = new char[100]; 
       
        // counter for hexadecimal number array 
        int i = 0; 
        while(n!=0) 
        {    
            // temporary variable to store remainder 
            int temp  = 0; 
           
            // storing remainder in temp variable. 
            temp = n % 16; 
           
            // check if temp < 10 
            if(temp < 10) 
            { 
                hexaDeciNum[i] = (char)(temp + 48); 
                i++; 
            } 
            else
            { 
                hexaDeciNum[i] = (char)(temp + 55); 
                i++; 
            } 
           
            n = n/16; 
        } 
       
        // printing hexadecimal number array in reverse order 
        for(int j=i-1; j>=0; j--) 
            System.out.print(hexaDeciNum[j]); 
    } 
      
    // driver program 
    public static void main (String[] args)  
    { 
        int n = 2545; 
        decToHexa(n); 
    } 
} 

Output

9F1

Check out the related programs:

Ask your questions about Java Program for decimal to hexadecimal conversion in Java and clarify your/others doubts by commenting. Documentation.

Please write to us at [email protected] to report any issue with the above content or for feedback.