note 99788 added to ref.gmp
| From: | Nitrogen at osu1 dot php dot net | Date: | Tue, 07 Sep 2010 03:02:06 +0000 |
| Subject: | note 99788 added to ref.gmp | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-172346@lists.php.net to get a copy of this message | ||
I made a function that can be used for converting numbers to any base you wish.. instead of
returning a string of pre-defined index of characters (i.e. 0-9a-z) you could simply make your own
of any length using the array of indexes it returns.
I looked around and didn't see anybody made one, I needed one for a simple compression
algorithm with only numbers, I've not actually made it yet but this was an initial idea.
<?php
// ConvertBase function explained:
// we add an array item $Input%$Base floored and divide $Input by $Base floored.
// repeat until $Input is no longer above 0.
function ConvertBase($Input,$Base=10) {
$Input=gmp_init($Input);
$Result=array();
for($i=0;$i<1||gmp_sign($Input)==1;$i++) {
$Result[]=gmp_intval(gmp_mod($Input,$Base));
$Input=gmp_div_q($Input,$Base);
}
$Result=array_reverse($Result);
return($Result);
}
// an example how gmp_strval($.., 36); could be achieved:
// the funny emergency number from The IT Crowd
// (leading zeroes aren't liked in gmp_init though)
$Input = '1189998819991197253';
// our example 36 characters used in gmp_strval($.., 36);
$Chars = '0123456789abcdefghijklmnopqrstuvwxyz';
// count the $Chars so they're all used
// or use your own number less than the length of $Chars
$Base = strlen($Chars);
// perform
$Result = ConvertBase($Input,$Base);
// replace the resulting index with the corrosponding characters of the index in $Chars
for($i=0;$i<count($Result);$i++)
$Result[$i]=$Chars{$Result[$i]};
// compare
printf("gmp_strval: %s\r\n",gmp_strval($Input,36));
printf("BaseConvert: %s\r\n",implode($Result));
/* OUTPUT:
gmp_strval: 91h7dixfq6h1
BaseConvert: 91h7dixfq6h1
*/
?>
The example shows a familiar result of course, but the idea of this function was so that you can use
whatever base you wish, and display entirely your own output to represent any number of choice.
Have fun,
Nitrogen.
----
Server IP: 69.147.83.197
Probable Submitter: 86.154.84.89
----
Manual Page -- http://www.php.net/manual/en/ref.gmp.php
Edit -- https://master.php.net/note/edit/99788
Del: integrated -- https://master.php.net/note/delete/99788/integrated
Del: useless -- https://master.php.net/note/delete/99788/useless
Del: bad code -- https://master.php.net/note/delete/99788/bad+code
Del: spam -- https://master.php.net/note/delete/99788/spam
Del: non-english -- https://master.php.net/note/delete/99788/non-english
Del: in docs -- https://master.php.net/note/delete/99788/in+docs
Del: other reasons-- https://master.php.net/note/delete/99788
Reject -- https://master.php.net/note/reject/99788
Search -- https://master.php.net/manage/user-notes.php