Translate integer to letters and vice versa (e.g. 0 = "A", 26 = "AA", 27 = "AB")

Translate integer to letters and vice versa (e.g. 0 = "A", 26 = "AA", 27 = "AB")

  1. Blog
  2. 15 November 2026
  3. 7 min read

Stefan Bogdanescu

Founder & Senior Architect

Decoding Base-26 Arithmetic for Excel-Style Column Labels

Converting an integer to a string representation where 0 is "A", 1 is "B", and so on, up to 26 being "AA", is a classic algorithmic puzzle. The forward direction—integer to letters—is often solved using a modified base-conversion technique. However, the reverse operation, converting those strings back to their original integers, requires careful attention to how the mathematical system differs from standard positional notation like decimal or binary.

The provided toAlpha function demonstrates this logic by treating the input as if it were in base-26 but with a twist: the mapping is 1-indexed relative to the digit values, not 0-indexed. In standard base-26 (where A=0 and Z=25), the number 26 would be 10 (one group of 26 and zero). In this specific "Excel column" system, there is no zero-value digit; every position contributes at least 1 to the total. This absence of a true zero makes the reverse calculation non-trivial if approached with standard modular arithmetic logic.

The Flaw in the Reverse Logic

The toNum function provided attempts to reconstruct the integer by iterating through the characters from left to right. The core issue lies in how the positional weight is applied. In standard base-N systems, you multiply the current accumulated value by the base and add the new digit's value. However, because this system lacks a zero digit, the simple "multiply and add" approach fails when reversing the specific toAlpha logic used in the forward pass.

Specifically, the line $num += ($alpha_flip[$data[$i]] + 1) inside the loop adds the current character's value directly to the accumulator without properly accounting for the fact that previous characters have been shifted into higher-order positions relative to the "no-zero" constraint. The logic tries to mimic base-26 expansion but incorrectly handles the offset required to align the calculated sum with the original integer input.

Correcting the Algorithm

To reverse the toAlpha function accurately, we must invert the forward process step-by-step. Since toAlpha processes the number from the most significant digit down to the least significant (conceptually), or rather, it peels off digits from the end while reducing the dividend, the reverse operation should interpret the string as a sum of values where each position's weight is determined by its distance from the rightmost character.

The correct approach treats the string as a sum of terms like value(char) * 26^position. However, because the digits are effectively "shifted" up by one (A represents a value of 1 in the lowest place, not 0), we must adjust our understanding of the base.

Consider the number 728 converting to "ABA".

  • 'A' is index 0 in the array, but in this system, it contributes 1 to the value of its position.
  • 'B' is index 1, contributing 2.

The mathematical structure for a string $S$ of length $L$ with characters $c_0, c_1, \dots, c_{L-1}$ (where $c_0$ is the leftmost character) is:

$$ Value = \sum_{i=0}^{L-1} (\text{index}(c_i) + 1) \times 26^{(L - 1 - i)} $$

Wait, this formula looks like standard base-26. Why did the forward function produce different results? The forward function uses a specific reduction: ($dividend - 1) % 26. This implies that the value of 'A' is treated as 0 for the modulo operation, but effectively contributes to the count differently.

Actually, let's look closer at the forward logic:

  1. If input $\le$ 25, return char directly (0->a, 25->z).
  2. If input > 25, add 1 to dividend, then loop.
    • Modulo is taken of (dividend - 1).
    • The new character index is that modulo.
    • The new dividend becomes floor((dividend - 1) / 26).

Notice the -1. This effectively treats 'A' as having a value of 0 in the modulo calculation, but the initial +1 to the dividend shifts the entire scale up. This creates a system where the range [0, 25] maps to single letters, and anything above starts using two or more letters.

To reverse this, we can simply interpret the string as if it were a standard base-26 number but with digits shifted by +1, except we must be careful about the "no zero" rule. However, a simpler way to think about the toAlpha system is that it maps integers $N$ to strings where the value of the string is $\sum (index(c_i) + 1) \times 26^{L-1-i}$ is incorrect.

Let's re-evaluate the specific math for "ABA".
Input: 728.
Forward trace:
dividend = 728 + 1 = 729.
Iter 1: modulo = (729 - 1) % 26 = 728 % 26 = 0. Char = 'a'. New dividend = floor(728 / 26) = 28.
Iter 2: modulo = (28 - 1) % 26 = 27 % 26 = 1. Char = 'b'. New dividend = floor(27 / 26) = 1.
Iter 3: modulo = (1 - 1) % 26 = 0. Char = 'a'. New dividend = 0. Stop.
Result: "aba".

Now, to reverse "aba":
We have characters with indices 0, 1, 0.
The forward process essentially calculated the number using a modified base-26 where the digits are $d_i \in [0, 25]$.
The value can be reconstructed by treating the string as if it were in base-26, but we must account for the fact that the "digits" used in the calculation were effectively $(index + 1)$ relative to the original input space? No.

Let's look at the value calculation directly from the forward steps:
The first character 'a' (index 0) was derived from $728 \pmod{26}$.
The second character 'b' (index 1) was derived from $(728 - 0) / 26 \pmod{26}$.
The third character 'a' (index 0) was derived from the remainder.

Actually, the system is exactly equivalent to interpreting the string as a base-26 number where 'a'=1, 'b'=2, ..., 'z'=26, but with a specific handling for the most significant digit logic? No.

Let's try the standard interpretation:
If we treat "aba" as digits $d_0=0, d_1=1, d_2=0$ in base 26.
Value = $0 \times 26^2 + 1 \times 26^1 + 0 \times 26^0 = 26$. This is clearly wrong (we need 728).

The correct interpretation of the toAlpha system is that it is a bijection between non-negative integers and strings, where the value of a string $s$ is:
$$ Value(s) = \sum_{i=0}^{L-1} (\text{index}(s[i]) + 1) \times 26^{L-1-i} $$
Wait, if we use this formula for "aba":
$i=0 ('a'), index=0$: $(0+1) \times 26^2 = 1 \times 676 = 676$.
$i=1 ('b'), index=1$: $(1+1) \times 26^1 = 2 \times 26 = 52$.
$i=2 ('a'), index=0$: $(0+1) \times 26^0 = 1 \times 1 = 1$.
Total = $676 + 52 + 1 = 729$.
But the input was 728. The function returns 728, but our formula gives 729.

Ah, the toAlpha function adds 1 to the dividend before processing. This means the internal calculation is actually for $N+1$.
So, toAlpha(728) computes the representation for 729 in a standard base-26 system where A=1...Z=26?
Let's check:
If we want to represent 729 in base 26 with digits 1-26:
$729 = 1 \times 26^2 + 2 \times 26^1 + 0 \dots$ wait, $1 \times 676 + 2 \times 26 + ? = 728$. Missing 1.
So $729 = 1 \times 676 + 2 \times 26 + 1$. Digits are 1, 2, 1. Which maps to A, B, A.
So the toAlpha function essentially converts $(N+1)$ to a base-26 string where digits are 1-based (A=1, B=2...).

Therefore, to reverse it, we must convert the string back to a number using the standard "digits 1-26" base-26 logic, and then subtract 1.

Implementation of the Fix

The corrected toNum function needs to:

  1. Parse the string assuming 'a' has value 1, 'b' has value 2, etc.
  2. Calculate the sum using powers of 26.
  3. Subtract 1 from the final result to get the original integer.

Here is the corrected logic in PHP:

function toNum($data) {
    $alphabet = ['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'];
    $alpha_flip = array_flip($alphabet);
    
    // Validate input characters just in case
    if (!preg_match('/^[a-z]+$/', $data)) {
        return false;
    }

    $length = strlen($data);
    $total = 0;

    for ($i = 0; $i < $length; $i++) {
        $charIndex = $alpha_flip[$data[$i]]; // 0 for 'a', 1 for 'b'
        $value = $charIndex + 1;            // Convert to 1-based value (1 for 'a')
        
        // Multiply by the appropriate power of 26 based on position
        $total += $value * pow(26, $length - 1 - $i);
    }

    return $total - 1;
}

This approach correctly handles the "ABA" case:

  • 'A' (0+1) $\times$ $26^2$ = 676
  • 'B' (1+1) $\times$ $26^1$ = 52
  • 'A' (0+1) $\times$ $26^0$ = 1
  • Sum = 729.
  • Subtract 1 = 728.

This matches the original input. The key insight is recognizing that the forward function operates on an offset integer ($N+1$) using a digit set that starts at 1, effectively creating a bijective base-26 system without a zero symbol. Any reverse implementation must respect this offset and the 1-based digit values to maintain mathematical consistency.

Our network