EN
Java - convert int to hex String
2
points
Short solution:
int number = 10;
String hexString = Integer.toHexString(number);
System.out.println(hexString); // a
Other simple examples:
System.out.println( Integer.toHexString(1) ); // 1
System.out.println( Integer.toHexString(9) ); // 9
System.out.println( Integer.toHexString(10) ); // a
System.out.println( Integer.toHexString(15) ); // f
System.out.println( Integer.toHexString(16) ); // 10
System.out.println( Integer.toHexString(17) ); // 11
System.out.println( Integer.toHexString(30) ); // 1e
System.out.println( Integer.toHexString(31) ); // 1f
System.out.println( Integer.toHexString(32) ); // 20
System.out.println( Integer.toHexString(33) ); // 21
In java to convert int to hex String we use Integer.toHexString()
method.
1. Print int decimal and hexadecimal values from 0 to 20
public class Example1 {
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
String hex = Integer.toHexString(i);
System.out.println("dec: " + i + ", hex: " + hex);
}
}
}
Output:
dec: 0, hex: 0
dec: 1, hex: 1
dec: 2, hex: 2
dec: 3, hex: 3
dec: 4, hex: 4
dec: 5, hex: 5
dec: 6, hex: 6
dec: 7, hex: 7
dec: 8, hex: 8
dec: 9, hex: 9
dec: 10, hex: a
dec: 11, hex: b
dec: 12, hex: c
dec: 13, hex: d
dec: 14, hex: e
dec: 15, hex: f
dec: 16, hex: 10
dec: 17, hex: 11
dec: 18, hex: 12
dec: 19, hex: 13
dec: 20, hex: 14
2. Convert hex String to int
public class Example2 {
public static void main(String[] args) {
String hexString = "a";
int number = Integer.valueOf(hexString, 16);
System.out.println(number); // 10
}
}
Output:
10