PHP function required to convert hex to lat & long
I have a question regarding lattitude and longitude encoding, the answer to which my brain refuses to produce.
I need to write a php function that takes the value '1446041F' and '447D1100' (Lat & Lng) does some processing (the bit I cannot fathom) and outputs '52.062297' and '0.191030'.
I am told the Lat & Lng are encoded to 4 bytes from a signed degrees, minutes and decimal minutes with a format as follows;
Latitude: SDDMM.MMMMM where 0≤DD≤90, S = [+|-], 0≤M≤9
Longitude: SDDDMM.MMMMM where 0≤DDD≤180, S = [+|-], 0≤M≤9
See that last bit, I've searched many sites but I still have no idea what that all means.
I'm aware this is a massive shot in the dark and it may be so si开发者_运维技巧mple that I am rightfully told to sit in the corner wearing the dunce hat but I am running low on hair to pull out!
Any advice is much appreciated.
Thanks, Matthew
The examples you gave, 1446041F
and 447D1100
are probably 32-bit signed integers in little-endian byte order.
They are to be read as follows:
1446041F -> 0x1F044614 -> 520373780
447D1100 -> 0x00117D44 -> 001146180
They can be interpreted in degrees and minutes like this:
520373780 -> 52 degrees, 03.73780 minutes
1146480 -> 0 degrees, 11.46480 minutes
The following function will convert the hex values you specified to degrees. I assume the values are integers like 0x447D1100 and the like. If I assume wrong and the input values are actually strings, let me know. I put this function into the public domain.
function hextolatlon($hex){
// Assume hex is a value like 0x1446041F or 0x447D1100
// Convert to a signed integer
$h=$hex&0xFF;
$h=($h<<8)|(($hex>>8)&0xFF);
$h=($h<<8)|(($hex>>16)&0xFF);
$h=($h<<8)|(($hex>>24)&0xFF);
$negative=($h>>31)!=0; // Get the sign
if($negative){
$h=~$h;
$h=$h&0x7FFFFFFF;
$h++;
}
// Convert to degrees and minutes
$degrees=floor($h/10000000);
$minutes=$h%10000000;
// Convert to full degrees
$degrees+=($minutes/100000.0) / 60.0;
if($negative)$degrees=-$degrees;
return $degrees;
}
Here's the PHP (the verbosity is for clarity):
function llconv($hex) {
// Pack hex string:
$bin = pack('H*', $hex);
// Unpack into integer (returns array):
$unpacked = unpack('V', $bin);
// Get first (and only) element:
$int = array_shift($unpacked);
// Decimalize minutes:
$degmin = $int / 100000;
// Get degrees:
$deg = (int)($degmin/100);
// Get minutes:
$min = $degmin - $deg*100;
// Return degress:
return round($deg + ($min/60), 6);
}
$long = '1446041F';
$lat = '447D1100';
$iLong = llconv($long);
$iLat = llconv($lat);
print "Out: $iLong x $iLat\n";
精彩评论