Advertisements

Aatul Palandurkar

Archive for April 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

Advertisements

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

Join 8,761 other followers

Tweets

%d bloggers like this: