Java convert decimal to hex

Let’s learn java convert decimal to hex.

Java convert decimal to hex

In program for decimal to hexadecimal conversion use Integer.toHexString() method,

import java.util.Scanner;

public class DecimalToHexaExample
{
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter decimal number : ");
      int decimalNumber = sc.nextInt(); 
      String str = Integer.toHexString(decimalNumber);
      System.out.println("The hexadecimal value is : " + str);
      sc.close();
   }
}



Output:

Please enter decimal number : 12
The hexadecimal value is : c


Let’s see using Integer.parseInt() method,

import java.util.*;

public class DecimalToHexaDemo
{
   public static void main(String[] args)
   {
      String strInput = "6c9";
      System.out.println(Integer.parseInt(strInput, 16));
   }
}



Output:

1737

In number system, decimal number has a base of ten. It has digits from 0 to 9. Whereas hexadecimal number has a base 16.

It has digits from 0 to 9 and A to F. Now let’s see the comparison through a table,

java convert decimal to hex

As you can see in the above table, from 0 to 9 the numbers are same in both number system.

After 9, 10 is denoted as ‘A’, 11 is denoted as ‘B’, 12 is denoted as ‘C’, 13 is denoted as ‘D’, 14 is denoted as ‘E’, 15 is denoted as ‘F’ in the hexadecimal system.

In the previous post we saw how to convert binary to decimal and decimal to binary java program. So, let’s see java program without using predefined method,

import java.util.Scanner;

public class DecimalToHexadecimal
{
   public static void main(String[] args)
   {
      int temp, decimalNumber;
      String hexaDecimal = "";
      char hexa[] = {'0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F'};
 
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter decimal number : ");
      decimalNumber = sc.nextInt();
 
      while(decimalNumber > 0)
      {
         temp = decimalNumber % 16;
         hexaDecimal = hexa[temp] + hexaDecimal;
         decimalNumber = decimalNumber / 16;
      }
 
      System.out.print("The hexadecimal value of is : " + hexaDecimal);      
      sc.close();
   }
}



Output:

Please enter decimal number : 10
The hexadecimal value is : A