0

I need to a function to convert an integer to the equivalent alpha ordered list index. For example:

1 = a
2 = b
.
.
.
26 = z
27 = aa
28 = ab
.
.
etc.

Currently I have the following which almost works but there's a small logic error somewhere that makes it not quite get it right (it goes ax, ay, bz, ba, bb, bc...):

function intToAlpha( int ) {

    var asciiStart = 97,
        alphaMax = 26,
        asciiCode,
        char,
        alpha = '',
        place,
        num,
        i;

    for ( i = 0; Math.pow(alphaMax, i) < int; i++ ) {

        place = Math.pow(alphaMax, i);        
        num = Math.floor( ( int / place ) % alphaMax);
        asciiCode = ( num == 0 ? alphaMax : num ) + asciiStart - 1;
        char = String.fromCharCode(asciiCode);
        alpha = char + alpha;

    }

    return alpha;
}

for (i = 1; i < 300; i++) {
    console.log( i + ': ' + intToAlpha(i) );
}
Josh Darnell
  • 11,304
  • 9
  • 38
  • 66
jbyrd
  • 5,287
  • 7
  • 52
  • 86

3 Answers3

2

This function is used in NVu/Kompozer/SeaMonkey Composer, with a small tweak to generate lower case directly:

function ConvertArabicToLetters(num)
{
  var letters = "";
  while (num > 0) {
    num--;
    letters = String.fromCharCode(97 + (num % 26)) + letters;
    num = Math.floor(num / 26);
  }
  return letters;
}
broofa
  • 37,461
  • 11
  • 73
  • 73
Neil
  • 54,642
  • 8
  • 60
  • 72
1

You need to make sure that you use the correct value when taking the mod.

function intToAlpha( int ) {
var asciiStart = 97,
    alphaMax = 26,
    asciiCode,
    char,
    alpha = "";
    while(int > 0) {
        char = String.fromCharCode(asciiStart + ((int-1) % alphaMax));
        alpha = char + alpha;
        int = Math.floor((int-1)/26);
    }
    return alpha;
}
Foo Bah
  • 25,660
  • 5
  • 55
  • 79
0

A while back I needed the same thing in SQL, so I asked (and answered) the question Multi-base conversion - using all combinations for URL shortener.

The thing that is making it complicated is that it's not a straight base conversion, as there is no character representing the zero digit.

I converted the SQL function into Javascript:

function tinyEncode(id) {

  var code, value, adder;

  var chars = 'abcdefghijklmnopqrstuvwxyz';

  if (id <= chars.length) {
    code = chars.substr(id - 1, 1);
  } else {
    id--;
    value = chars.length;
    adder = 0;
    while (id >= value * (chars.length + 1) + adder) {
      adder += value;
      value *= chars.length;
    }
    code = chars.substr(Math.floor((id - adder) / value) - 1, 1);
    id = (id - adder) % value;
    while (value > 1) {
      value = Math.floor(value / chars.length);
      code += chars.substr(Math.floor(id / value), 1);
      id = id % value;
    }
  }
  return code;
}

Demo: http://jsfiddle.net/Guffa/mstBe/

Community
  • 1
  • 1
Guffa
  • 687,336
  • 108
  • 737
  • 1,005