Convert Hexadecimal to Decimal in Java
Problem
Each hexadecimal digit is worth a power of sixteen, and the letters A to F stand for 10 to 15, so 7F3A equals 7×4096 + 15×256 + 3×16 + 10 = 32570.
Given a string holding a hexadecimal number, print its decimal value, accepting both uppercase and lowercase letters.
Java Program
public class HexadecimalToDecimal {
public static void main(String[] args) {
String hex = "7F3A";
int decimal = 0;
for (char c : hex.toCharArray()) {
char upper = Character.toUpperCase(c); // accept "7f3a" as well as "7F3A"
int value;
if (upper >= '0' && upper <= '9') {
value = upper - '0';
} else if (upper >= 'A' && upper <= 'F') {
value = upper - 'A' + 10;
} else {
System.out.println("Not a valid hex digit: " + c);
return;
}
decimal = decimal * 16 + value;
}
System.out.println("Decimal of " + hex + ": " + decimal);
}
}Output
Core Logic
Each character is first turned into its value from 0 to 15, then folded into a running total that is multiplied by 16 at every step.
- 1
Character.toUpperCase(c)lets'f'and'F'be handled the same way. - 2Digits
'0'to'9'map toupper - '0'; letters'A'to'F'map toupper - 'A' + 10. - 3Anything else is reported as an invalid hex digit.
- 4
decimal * 16 + valueadds each digit at the right power of sixteen.
7F3A: 7 → 7×16 + 15 = 127 → 127×16 + 3 = 2035 → 2035×16 + 10 = 32570.Key Point: upper - 'A' + 10 works because the letters A to F have consecutive character codes, so their distance from 'A' is 0 to 5.
Why: Each of the n characters is converted and added once.
Key Concepts
Approach 2: Using Integer.parseInt() and Integer.decode()
public class HexadecimalToDecimalBuiltIn {
public static void main(String[] args) {
String hex = "7F3A";
System.out.println("Decimal of " + hex + ": " + Integer.parseInt(hex, 16));
String withPrefix = "0x7F3A";
System.out.println("Decimal of " + withPrefix + ": " + Integer.decode(withPrefix)); // decode understands 0x
}
}
Output
Core Logic
parseInt with radix 16 handles bare hex digits, while Integer.decode also understands a 0x or # prefix.
- 1
Integer.parseInt("7F3A", 16)returns32570. - 2
parseIntwould reject"0x7F3A", because the prefix isn't a hex digit. - 3
Integer.decode("0x7F3A")recognises the prefix and returns the same value.
32570.Key Point: Use decode for user-facing input such as colour codes (#FF8800), where a prefix is common.
Why: Both methods parse the string in a single pass.
Key Concepts
Interview Questions
How do you parse hex with a 0x prefix?
Integer.decode("0x1F") understands the prefix; Integer.parseInt("1F", 16) needs it removed.
How do you parse a hex value larger than an int?
Long.parseLong(hex, 16) or new BigInteger(hex, 16).