note 94874 added to function.base-convert
| From: | Theriault at osu1 dot php dot net | Date: | Mon, 30 Nov 2009 10:11:36 +0000 |
| Subject: | note 94874 added to function.base-convert | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-163396@lists.php.net to get a copy of this message | ||
If you would like to convert numbers into just the uppercase alphabet base and vice-versa (e.g. the
column names in a Microsoft Windows Excel sheet..A-Z, AA-ZZ, AAA-ZZZ, ...), the following functions
will do this.
<?php
/**
* Converts an integer into the alphabet base (A-Z).
*
* @param int $n This is the number to convert.
* @return string The converted number.
* @author Theriault
*
*/
function num2alpha($n) {
$r = '';
for ($i = 1; $n >= 0 && $i < 10; $i++) {
$r = chr(0x41 + ($n % pow(26, $i) / pow(26, $i - 1))) . $r;
$n -= pow(26, $i);
}
return $r;
}
/**
* Converts an alphabetic string into an integer.
*
* @param int $n This is the number to convert.
* @return string The converted number.
* @author Theriault
*
*/
function alpha2num($a) {
$r = 0;
$l = strlen($a);
for ($i = 0; $i < $l; $i++) {
$r += pow(26, $i) * (ord($a[$l - $i - 1]) - 0x40);
}
return $r - 1;
}
?>
Microsoft Windows Excel stops at IV (255), but this function can handle much larger. However,
English words will start to form after a while and some may be offensive, so be careful.
----
Server IP: 64.71.164.2
Probable Submitter: 76.25.107.41
----
Manual Page -- http://www.php.net/manual/en/function.base-convert.php
Edit -- https://master.php.net/note/edit/94874
Del: integrated -- https://master.php.net/note/delete/94874/integrated
Del: useless -- https://master.php.net/note/delete/94874/useless
Del: bad code -- https://master.php.net/note/delete/94874/bad+code
Del: spam -- https://master.php.net/note/delete/94874/spam
Del: non-english -- https://master.php.net/note/delete/94874/non-english
Del: in docs -- https://master.php.net/note/delete/94874/in+docs
Del: other reasons-- https://master.php.net/note/delete/94874
Reject -- https://master.php.net/note/reject/94874
Search -- https://master.php.net/manage/user-notes.php