I'm trying to write a function that'll convert an integer to a string like this, but I can't figure out the logic... :(
1 = a
5 = e
27 = aa
28 = ab
etc...
Can anyone help? I'm really niffed that I can't wrap my head around how to write this... :(
Long list of them here:
/*
* Convert an integer to a string of uppercase letters (A-Z, AA-ZZ, AAA-ZZZ, etc.)
*/
function num2alpha($n)
{
for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
$r = chr($n%26 + 0x41) . $r;
return $r;
}
/*
* Convert a string of uppercase letters to an integer.
*/
function alpha2num($a)
{
$l = strlen($a);
$n = 0;
for($i = 0; $i < $l; $i++)
$n = $n*26 + ord($a[$i]) - 0x40;
return $n-1;
}
I'll add this answer to sum up the comments regarding the misuse of base-26.
A common first reaction when confronted with this problem is to think "There are 26 letters, so this must be base-26! All I need to do is map each letter to its corresponding number".
But this is not base-26. It's easy to see why: there is no zero!
In base-26, the number twenty-six is the first number with two digits, and is written "10". In this counting system, twenty-six has a single digit, "Z", and the first two-digit number is twenty-seven.
But what if we make A=0, ..., Z=25? This way we have a zero and the first two-digit number becomes twenty-six. So far so good. How do we write twenty-six now? That's "AA". But... isn't A=0? Ooops! A = AA = AAA = "0" = "00" = "000".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With