LAST UPDATED: DECEMBER 1, 2020
How to convert Java Decimal to HexaDecimal
In Java, Decimal can be converted into HexaDecimal either using Integer.toHexString() method or own custom code. Let's see the examples.
1. Integer.toHexString()
method
The toHexString() method is a part of Integer class that converts the decimal into hexadecimal strings which further can be converted into an int
or float
type.
Example 1:
Here, the decimal values are converted into hexadecimal strings by using the toHexString()
method.
public class StudyTonight
{
public static void main(String args[])
{
int d1 = 7;
int d2 = -232;
int d3 = 90902;
String h1 = Integer.toHexString(d1);
String h2 = Integer.toHexString(d2);
String h3 = Integer.toHexString(d3);
System.out.println("Binary value is : " +h1);
System.out.println("Binary value is : " +h2);
System.out.println("Binary value is : " +h3);
}
}
Binary value is : 7
Binary value is : ffffff18
Binary value is : 16316
Example 2:
The decimal values can be converted into hexadecimal values using custom logic.
public class StudyTonight
{
public static void main(String [] args)
{
int dec = 34673;
int r;
String hex = "";
char hexch[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(dec>0)
{
r = dec % 16;
hex = hexch[r]+hex;
dec = dec/16;
}
System.out.println("The hexadecimal value is " +hex);
}
}
The hexadecimal value is 8771