Languages
[Edit]
EN

Java - convert hex to long

1 points
Created by:
Root-ssh
175400

Short solution:

String hex = "4a817c8f600";
long number = Long.parseLong(hex, 16);

System.out.println(number); // 5120000062976

The best way to convert hex String to long in java is to use Long.parseLong() method.

Syntax:

Long.parseLong(String hexString, int radix)

1. Convert couple of different hex to long

public class Example1 {

    public static void main(String[] args) {

        System.out.println( Long.parseLong("5", 16) );  // 5
        System.out.println( Long.parseLong("a", 16) );  // 10
        System.out.println( Long.parseLong("b", 16) );  // 11
        System.out.println( Long.parseLong("f", 16) );  // 15
        System.out.println( Long.parseLong("10", 16) ); // 16
        System.out.println( Long.parseLong("1f", 16) ); // 31
        System.out.println( Long.parseLong("20", 16) ); // 32
        System.out.println( Long.parseLong("21", 16) ); // 33

        // 3002399751580330
        System.out.println( Long.parseLong("aaaaaaaaaaaaa", 16) );
    }
}

Output:

5
10
11
15
16
31
32
33
3002399751580330

2. Convert hex to long in for loop

public class Example2 {

    public static void main(String[] args) {

        System.out.println("           Hex -  Dec");

        long number = 10_000_000_123L;
        for (int i = 0; i < 10; i++) {

            String hex = Long.toHexString(number);
            long backToLong = Long.parseLong(hex, 16);

            System.out.println(String.format("%14s", hex) + " - "
                    + String.format("%14s", backToLong));

            number *= 2;
        }
    }
}

Output:

         Hex -  Dec
   2540be47b -  10000000123
   4a817c8f6 -  20000000246
   9502f91ec -  40000000492
  12a05f23d8 -  80000000984
  2540be47b0 - 160000001968
  4a817c8f60 - 320000003936
  9502f91ec0 - 640000007872
 12a05f23d80 - 1280000015744
 2540be47b00 - 2560000031488
 4a817c8f600 - 5120000062976

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join