Reputation: 143
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;
}
Upvotes: 1
Views: 2948
Reputation: 159165
You need to first parse the hex value to an int
, then multiply that by divide that by 1e-7
(faster to multiply by 1e-7
that divide by 1e7
)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
Upvotes: 3
Reputation: 41686
The first number looks very easy: just divide the int
result by 10.0e6, which is 10 millions.
Upvotes: 0