1

I'm migrating a script from C to PHP (http://svn.stellman-greene.com/mgrs_to_utm/trunk/) and I have a problem with this concept in mgrs_to_utm.c:

Letters[0] = (toupper(MGRS[j]) - (long)'A');
if ((Letters[0] == LETTER_I) || (Letters[0] == LETTER_O))

MGRS[j] is a part of string, but WTF I can substract a (long)'A' to a LETTER??

LETTER_I is an integer (defined in mgrs_to_utm.h).

I have in mind PHP and I can't found the logic to this operation.

Thanks a lot for your help :)

3
  • that looks like an ASCii substraction to adjust a value in the array letter Commented Aug 20, 2012 at 10:16
  • I don't know about the typecasting to LONG but this is actually very common to convert a letter from ASCII to the number of the letter in the alphabet. Characters are just normal integers, so having a char c it's okay to do toupper(c) - 'A'. Commented Aug 20, 2012 at 10:16
  • 1
    ord(strtoupper(MGRS[j])) - ord('A') I think, this php is equivalent to that c code. But note from manual, it won't always return US-ASCII value. Commented Aug 20, 2012 at 10:19

1 Answer 1

3

In ASCII, the character 'A' has value 65, so Letters[0] effectively contains an offset into the alphabet (A being 0).

If MGRS[j] is 'I' (73) then we take 'A' (65) from it to leave 8

A B C D E F G H I J K...
0 1 2 3 4 5 6 7 8 9 10

The code is pretty much the same as:

if ( MGRS[j] == 'I' || MGRS[j] == 'O' || MGRS[j] == 'i' || MGRS[j] == 'o') 
Sign up to request clarification or add additional context in comments.

2 Comments

Ok :) A PHP implement would be $Letters[0] = ord(strtoupper($MGRS[$j])) - ord('A'); if (($Letters[0] == $LETTER_I) || ($Letters[0] == $LETTER_O)) {... Using ord PHP function php.net/manual/en/function.ord.php. I can understand now the rest of code :)
Beware that the value of the letter is actually used in calculation in a couple places: grid_northing = (double)(letters[2]) * ONEHT + false_northing; grid_easting = (double)((letters[1]) - ltr2_low_value + 1) * ONEHT;. To get the value, I would do intval($letters[2], 36) - 10.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.