Phobox Phobox - 3 months ago 13
Java Question

Convert Hex to Decimal (Lat / Lon)?

I got a latitude and longitude values in hexadecimal:

0AF6CF83
D89B2933


Converting them to decimal I got...

183947139
-660920013


The problem is, how to get those decimals in the following format using Java?

18.3947139
-66.0920013


This is how I actually converting Hex to Decimal:

public static int hex2Decimal(String s) {
long longValue = Long.parseLong(s, 16);
int intValue = (int)longValue;
return intValue;
}

Answer

You need to first parse the hex value to an int, then multiply that by 1e-7 (faster to multiply by 1e-7 that divide by 1e7) divide that by 1e7.
   Thanks to @RolandIllig for pointing out the precision issue.

However, Integer.parseInt() will not allow parsing an 8 digit hex value to a negative integer value, i.e. when the high bit is on.

In Java 8, you'd do this:

public static double hex2Decimal(String s) {
    return Integer.parseUnsignedInt(s, 16) / 1e7;
}

If your code needs to run on Java versions before 8, do this:

public static double hex2Decimal(String s) {
    return (int)Long.parseLong(s, 16) / 1e7;
}

Test

System.out.println(hex2Decimal("0AF6CF83"));
System.out.println(hex2Decimal("D89B2933"));

Output

18.3947139
-66.0920013