Convert decimal to hexadecimal in Java
In this post, you will learn how to convert decimal to hexadecimal using the Java programming language.
A decimal number is a base-10 number system. It ranges from 0 to 9 i.e., 0,1,2,3,4,5,6,7,8,9. Any combination of digits is a decimal number such as 61, 22, 912, 0, 5 etc. The main advantages of the decimal number system are easy-to-read, used by humans and easy to manipulate.
Hexadecimal describes a base-16 number system. Hexadecimal Number System is generally used in computer programming and Microprocessors. It is also helpful to describe colours on web pages. The main advantage of a Hexadecimal Number is that it is exceptionally compact and by utilizing a base of 16 means that the number of digits used to address a given number is normally less than in binary or decimal.
Java program to convert decimal to hexadecimal using Integer.toHexString()
Java provides a built-in Integer.toHexString() function to convert various values to a hexadecimal number. This function returns hexadecimal value.
// Java program to convert decimal to hexadecimal
public class DecimalToHexExample1{
public static void main(String args[]){
System.out.println("10 : "+Integer.toHexString(10));
System.out.println("26 : "+Integer.toHexString(26));
System.out.println("5 : "+Integer.toHexString(5));
System.out.println("14 : "+Integer.toHexString(14));
System.out.println("16 : "+Integer.toHexString(16));
}
}
Output of the above code:
10 : a
26 : 1a
5 : 5
14 : e
16 : 10
Java convert decimal to hexadecimal using Loop
For converting a decimal to hexadecimal, the standard mathematical approach is to divide the number by 16 until it reduces to zero. The sequence of remainders from last to first in a hex structure is the hexadecimal number system of the given decimal number. The following example demonstrates this -
public class DecimalToHex
{
public static void main(String args[])
{
int num = 26;
// For storing remainder
int rem;
// For storing result
String result="";
// Digits in hexadecimal number system
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(num>0)
{
rem=num%16;
result=hex[rem]+result;
num=num/16;
}
System.out.println("Decimal to hexadecimal: "+result);
}
}
Output of the above code:
Decimal to hexadecimal: 1A
Related Articles
Sort array in ascending order Javanth prime number in Java
Java random number between 1 and 10
Determinant of a matrix in Java
Find the greatest of three numbers in Java
Capitalize first letter of each word Java
Convert binary to decimal in Java
Convert decimal to binary in Java
Convert decimal to octal in Java
Simple interest program in Java
Check whether the given number is even or odd in java
Print prime numbers from 1 to 100 in Java
Java prime number program
Java program to convert celsius to fahrenheit
Fibonacci series program in Java
Java program to check leap year
Java program to find factorial of a number