Languages
[Edit]
EN

Java - convert hex to long

1 points
Created by:
Root-ssh
7608

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

 

Java conversion

Hey 👋
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.