将整数转换为alpha等效列表

时间:2011-09-16 22:08:30

标签: javascript integer alpha

我需要一个函数将整数转换为等效的alpha有序列表索引。例如:

1 = a 2 = b



26 = z
27 = aa
28 = ab



目前我有以下哪些 几乎 有效,但是某个地方出现了一个小的逻辑错误,导致它不能正常运行(它斧头,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) );
}

3 个答案:

答案 0 :(得分:2)

此功能用于NVu / Kompozer / SeaMonkey Composer,只需稍加调整即可直接生成小写:

function ConvertArabicToLetters(num)
{
  var letters = "";
  while (num > 0) {
    num--;
    letters = String.fromCharCode(97 + (num % 26)) + letters;
    num = Math.floor(num / 26);
  }
  return letters;
}

答案 1 :(得分:1)

你需要确保在服用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;
}

答案 2 :(得分:0)

前段时间我在SQL中需要相同的东西,所以我问(并回答)问题Multi-base conversion - using all combinations for URL shortener

让它变得复杂的是它不是直接的基本转换,因为没有代表零位的字符。

我将SQL函数转换为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;
}

演示:http://jsfiddle.net/Guffa/mstBe/