Converting Numbers into Bijective Base-26

So recently I was working on a side project where I wanted to change a sequence of numbers to a sequence of characters: 0 = A, 1 = B … 25 = Z, 26 = AA. Similar to how Microsoft Excel and other spreadsheets number their column headers.

My first thought was its just a Base10 to Base26 conversion and then map the resulting values of each digit to their corresponding character.

Nope, that does not work. If you think about it, if  A = 0 and B = 1 then 10 = BA and you get a sequence of A,B,C…Z, BA, BB, BC. That’s correct Base26 but its not what I wanted.

After some searching with google, I found out that the name of this kind of numbering system is called Bijective Base26 or Base 26 without a zero. Thanks Wikipedia!

After some further googling to find examples of an algorithm, I cobbled together a few chunks of pseudo code (props to yabob) to come up with the following ruby implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
ALPHABET = %w(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z)
def alphabase(n, letters = [])
  len = ALPHABET.length
 
  if (n >= len)
    alphabase(n/len - 1, letters)
    n = n % len
  end
 
  letters << ALPHABET[n]
 
  letters.join
 
end
alphabase(0) => 'A'
alphabase(25) => 'Z'
alphabase(26) => 'AA'

Maybe someone will find this useful. It’s also probably a fun interview question to ask a candidate

Leave a Reply