EN
Java - convert hex to long
1 points
Short solution:
xxxxxxxxxx
1
String hex = "4a817c8f600";
2
long number = Long.parseLong(hex, 16);
3
4
System.out.println(number); // 5120000062976
The best way to convert hex String to long in java is to use Long.parseLong() method.
Syntax:
xxxxxxxxxx
1
Long.parseLong(String hexString, int radix)
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
5
System.out.println( Long.parseLong("5", 16) ); // 5
6
System.out.println( Long.parseLong("a", 16) ); // 10
7
System.out.println( Long.parseLong("b", 16) ); // 11
8
System.out.println( Long.parseLong("f", 16) ); // 15
9
System.out.println( Long.parseLong("10", 16) ); // 16
10
System.out.println( Long.parseLong("1f", 16) ); // 31
11
System.out.println( Long.parseLong("20", 16) ); // 32
12
System.out.println( Long.parseLong("21", 16) ); // 33
13
14
// 3002399751580330
15
System.out.println( Long.parseLong("aaaaaaaaaaaaa", 16) );
16
}
17
}
Output:
xxxxxxxxxx
1
5
2
10
3
11
4
15
5
16
6
31
7
32
8
33
9
3002399751580330
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
5
System.out.println(" Hex - Dec");
6
7
long number = 10_000_000_123L;
8
for (int i = 0; i < 10; i++) {
9
10
String hex = Long.toHexString(number);
11
long backToLong = Long.parseLong(hex, 16);
12
13
System.out.println(String.format("%14s", hex) + " - "
14
+ String.format("%14s", backToLong));
15
16
number *= 2;
17
}
18
}
19
}
Output:
xxxxxxxxxx
1
Hex - Dec
2
2540be47b - 10000000123
3
4a817c8f6 - 20000000246
4
9502f91ec - 40000000492
5
12a05f23d8 - 80000000984
6
2540be47b0 - 160000001968
7
4a817c8f60 - 320000003936
8
9502f91ec0 - 640000007872
9
12a05f23d80 - 1280000015744
10
2540be47b00 - 2560000031488
11
4a817c8f600 - 5120000062976