There are two following ways to convert a 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.
Program 1: Decimal to hexadecimal Using toHexString() method
The toHexString()
method accepts integer number as argument and returns equivalent hexadecimal number as a String. The syntax of this method is:
public static String toHexString(int i)
Let’s write a program to convert a given int number to hex number.
class JavaExample { public static void main(String args[]) { //give int value int num = 10335; // toHexString() converts int to hex String str = Integer.toHexString(num); System.out.println("Decimal to Hexadecimal: "+str); } }
Output:
Decimal to Hexadecimal: 285f
Get the input number from user: Same program as above, just used Scanner class to get the decimal number input from user.
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
Program 2: Decimal to hexadecimal without using predefined method
In this method, we are not using the predefined method for conversion. We have written a logic to convert the given decimal number to hex.
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
Leave a Reply