note 117830 added to function.base-convert

From: Date: Sun, 16 Aug 2015 22:49:36 +0000
Subject: note 117830 added to function.base-convert
Groups: php.notes 
Request: Send a blank email to php-notes+get-203364@lists.php.net to get a copy of this message
I wrote this as part of a college assignment to shorten urls. It works for any base and with any range of characters, eg. A-Za-z0-9 etc. Hope it helps someone. <?php $base = range(0, 1); $number = 255; function translate($base, $number){ $array = array(); $n = count($base); $i = $number; while(true){ /* by dividing $i % $n we can get the remainder after the number has * been divided by the base. Subtracting the result from $i (number), and dividing * by $n (base) we reassign the result to $i, thus moving on to the next smallest * exponent, and around for another go of the loop. It continues doing this, churning * out the remainders until $i <= 0 at which point it breaks. */ if($i <= 0){ break; }else{ $r = ($i % $n); //reassign the value of $i $i = ($i - $r) / $n; $array[] = $base[$r]; } } $string = implode("", $array); return $string; } $string = translate($base, $number); echo $string; // prints 11111111 ? ---- Server IP: 72.52.91.14 Probable Submitter: 46.7.86.198 ---- Manual Page -- http://php.net/manual/en/function.base-convert.php Edit -- https://master.php.net/note/edit/117830 Del: integrated -- https://master.php.net/note/delete/117830/integrated Del: useless -- https://master.php.net/note/delete/117830/useless Del: bad code -- https://master.php.net/note/delete/117830/bad+code Del: spam -- https://master.php.net/note/delete/117830/spam Del: non-english -- https://master.php.net/note/delete/117830/non-english Del: in docs -- https://master.php.net/note/delete/117830/in+docs Del: other reasons-- https://master.php.net/note/delete/117830 Reject -- https://master.php.net/note/reject/117830 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#203364) next »