EN
Java - convert long to hex String
14
points
Short solution:
long number = 10;
String hexString = Long.toHexString(number);
System.out.println(hexString); // a
Other simple examples:
System.out.println( Long.toHexString(1) ); // 1
System.out.println( Long.toHexString(9) ); // 9
System.out.println( Long.toHexString(10) ); // a
System.out.println( Long.toHexString(15) ); // f
System.out.println( Long.toHexString(16) ); // 10
System.out.println( Long.toHexString(17) ); // 11
System.out.println( Long.toHexString(30) ); // 1e
System.out.println( Long.toHexString(31) ); // 1f
System.out.println( Long.toHexString(32) ); // 20
System.out.println( Long.toHexString(33) ); // 21
1. Print long and hex values from 0 to 20
public class Example1 {
public static void main(String[] args) {
for (long number = 0; number <= 20; number++) {
String hex = Long.toHexString(number);
System.out.println("dec: " + number + ", 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 long
public class Example2 {
public static void main(String[] args) {
String hexString = "a";
long number = Long.valueOf(hexString, 16);
System.out.println(number); // 10
}
}
Output:
10