Java program to convert decimal to hexadecimal
There are two following ways to convert Decimal number to hexadecimal number:
1) Using toHexString() method of Integer class.
2) Do conversion by writing your own logic without using any predefined methods.
2) Do conversion by writing your own logic without using any predefined methods.
Method 1: Decimal to hexadecimal Using toHexString() method
import java.util.Scanner;
class DecimalToHexExample
{
public static void main(String args[])
{
Scanner input = new Scanner( System.in );
System.out.print("Enter a decimal number : ");
int num =input.nextInt();
// calling method toHexString()
String str = Integer.toHexString(num);
System.out.println("Method 1: Decimal to hexadecimal: "+str);
}
}
Output:
Enter a decimal number : 123
Method 1: Decimal to hexadecimal: 7b
Method 2: Decimal to hexadecimal without using predefined method
import java.util.Scanner;
class DecimalToHexExample
{
public static void main(String args[])
{
Scanner input = new Scanner( System.in );
System.out.print("Enter a decimal number : ");
int num =input.nextInt();
// For storing remainder
int rem;
// For storing result
String str2="";
// 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;
str2=hex[rem]+str2;
num=num/16;
}
System.out.println("Method 2: Decimal to hexadecimal: "+str2);
}
}
Output:
Enter a decimal number : 123
Method 2: Decimal to hexadecimal: 7B