Convert an integer of any size to any letter from A to Z

This is one of those little problems that seem so simple that any bone-head could figure it out. That’s why I felt particularly stupid for struggling with it. Of course, the first thing I did was Google for the answer and since that did not help initially, I thought I should now post the solution.

Example use-case situation:

I’m rendering pins on a map using the Google API. I’m choosing my pins based on file names like ‘blue-a.png’, ‘blue-b.png’, blue-c.png’, and so forth. In this way, I can have a legend on the left hand side of my view with lettered pins that correspond to the same lettered pins on the map at right in the view. The kicker is that when I get to Z, I need to start all over again at A. Since I can never know how many pins might go on the map, I need this looping-back-to-A thing to go on forever, no matter how high my integers get.

The programming problem:

I need to provide an integer to a function and get back a corresponding letter from ‘a’ to ‘z’. If I give the number 0, I should get back the letter ‘a’. If I give the number 25, I should get back the letter ‘z’. If I give the number 26, I should get back the letter ‘a’. This looping-back-to-A thing needs to go on forever, so that if I give the number 326 I should get back the letter ‘o’ or if I give the number 493, I should get back the letter ‘z’. Oh, and I need it in both Java and JavaScript.

The solution:

Like I said, I feel like an idiot for struggling with this, but I eventually got it and here it is:

In Java

public static String toLetter(Integer ndx) {
    int r=ndx%26;
    return Character.toString((char)(r+97));
}

In JavaScript

function getAToZByIndex(ndx){
    var r = ndx%26;
    return String.fromCharCode(r+97);
}