note 95086 added to function.base-convert
| From: | sebastien at cslavoie dot com | Date: | Sat, 12 Dec 2009 20:10:17 +0000 |
| Subject: | note 95086 added to function.base-convert | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-163892@lists.php.net to get a copy of this message | ||
From all your suggestions and the algorythmn on this page:
http://www.cut-the-knot.org/recurrence/conversion.shtml
Here is a super-fast, customizable base converter.
<?php
function convert_int($input, $n=62) { // n <= 62
static $arr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if ($input < $n)
return $arr[$input];
else
return convert_int(floor($input/$n), $n) . $arr[$input % $n];
}
function unconvert_int($input, $n=62) { // n <= 62
static $arr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (strlen($input) == 0)
return 0;
else
return unconvert_int(substr($input, 0, -1), $n) * $n + strpos($arr, substr($input, -1));
}
?>
It only works with int, but you could always call it twice.
Example with hexadecimal -> binary:
<?php convert_int(unconvert_int("1F", 16), 2) ?>
I use this snippet to compress timestamps. Like this:
<?php
$reference = 1230789600; // Jan 1st 2009
echo $compressed = convert_int(time() - $reference); // 21HS4
echo $timestamp = unconvert_int($c) + $reference; // 1260647688 at this moment
?>
----
Server IP: 72.55.140.6
Probable Submitter: 74.59.109.195
----
Manual Page -- http://www.php.net/manual/en/function.base-convert.php
Edit -- https://master.php.net/note/edit/95086
Del: integrated -- https://master.php.net/note/delete/95086/integrated
Del: useless -- https://master.php.net/note/delete/95086/useless
Del: bad code -- https://master.php.net/note/delete/95086/bad+code
Del: spam -- https://master.php.net/note/delete/95086/spam
Del: non-english -- https://master.php.net/note/delete/95086/non-english
Del: in docs -- https://master.php.net/note/delete/95086/in+docs
Del: other reasons-- https://master.php.net/note/delete/95086
Reject -- https://master.php.net/note/reject/95086
Search -- https://master.php.net/manage/user-notes.php