Advertisements

Aatul Palandurkar

Java Program to convert Decimal values to Hexadecimal values

Posted on: April 20, 2016

Objectives :

  • How to convert Decimal to Hexadecimal in Java?

 

Java Program to convert Decimal values to Hexadecimal values : 


import java.util.Scanner;

public class DecimalToHexadecimal {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter decimal number you like: ");
int deci = input.nextInt();

System.out.println("The hexadecimal number for decimal "
+ deci + " is " + convert(deci));
}

public static String convert(int decimal) {
String hex = "";

while (decimal != 0) {
int hexValue = decimal % 16;
hex = toHexadecimal(hexValue) + hex;
decimal = decimal / 16;
}

return hex;
}

public static char toHexadecimal(int hexValue) {
if (hexValue <= 9 && hexValue >= 0) {
return (char) (hexValue + '0');
} else {
return (char) (hexValue - 10 + 'A');
}
}
}

Output :
Enter decimal number you like: 1234
The hexadecimal number for decimal 1234 is 4D2

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Advertisements

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 8,305 other followers

Tweets

%d bloggers like this: