Converting Decimal to Hex in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.*;
 
public class DecimalToHex {
 
	public static void main(String[] args) {
		int decimal;
		Scanner kb = new Scanner(System.in);
 
		System.out.println("Enter a number in decimal: ");
		decimal = kb.nextInt();
 
		System.out.println("The hex equivalent is: " + decimalToHex(decimal));			
 
	}
 
	public static String decimalToHex(int decimal) {
		String hex = "";
		while(decimal != 0) {
			int hexValue = decimal % 16;
			hex = toHexChar(hexValue) + hex;
			decimal /= 16;
		}
		return hex;
	}
 
	public static char toHexChar(int digit) {
		if(digit <= 9 && digit >= 0)
			return (char) (digit + '0');
		else
			return ((char) (digit - 10 + 'A'));		
	}
 
}
Share This!

Leave a Reply

Your email address will not be published.