EN
Java - convert hex to int
4
points
Short solution:
String hex = "a";
int number = Integer.parseInt(hex, 16);
System.out.println(number); // 10
The best way to convert hex String to int in java is to use Integer.parseInt()
method.
Syntax:
Integer.parseInt(String hexString, int radix)
1. Convert couple of different hex to int
public class Example1 {
public static void main(String[] args) {
System.out.println( Integer.parseInt("5", 16) ); // 5
System.out.println( Integer.parseInt("a", 16) ); // 10
System.out.println( Integer.parseInt("b", 16) ); // 11
System.out.println( Integer.parseInt("f", 16) ); // 15
System.out.println( Integer.parseInt("10", 16) ); // 16
System.out.println( Integer.parseInt("1f", 16) ); // 31
System.out.println( Integer.parseInt("20", 16) ); // 32
System.out.println( Integer.parseInt("21", 16) ); // 33
}
}
Output:
5
10
11
15
16
31
32
33
2. Convert hex to int in loop - from 0 to 20
public class Example2 {
public static void main(String[] args) {
System.out.println("Hex | Dec");
for (int number = 0; number <= 16; number++) {
String hex = Integer.toHexString(number);
int backToDecimal = Integer.parseInt(hex, 16);
System.out.println(String.format("%3s", hex) + " - "
+ String.format("%3s", backToDecimal));
}
}
}
Output:
Hex | Dec
0 - 0
1 - 1
2 - 2
3 - 3
4 - 4
5 - 5
6 - 6
7 - 7
8 - 8
9 - 9
a - 10
b - 11
c - 12
d - 13
e - 14
f - 15
10 - 16