note 55204 deleted from function.base-convert by danbrown

From: Date: Sat, 02 Jul 2011 15:40:17 +0000
Subject: note 55204 deleted from function.base-convert by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-181170@lists.php.net to get a copy of this message
Note Submitter: rithiur at mbnet dot fi ---- Here is a simple function that works like the function provided by Mr. Fips (See below) with the exception that this can convert numbers of any size. However, note that as the division is performed manually to the number, this function is not very efficient and may not be suitable for converting strings with more than a few hundred numbers (depending on the number bases). <?php function custombase_convert_big ($numstring, $frombase, $tobase) { $from_count = strlen($frombase); $to_count = strlen($tobase); $length = strlen($numstring); $result = ''; for ($i = 0; $i < $length; $i++) { $number[$i] = strpos($frombase, $numstring{$i}); } do // Loop until whole number is converted { $divide = 0; $newlen = 0; for ($i = 0; $i < $length; $i++) // Perform division manually (which is why this works with big numbers) { $divide = $divide * $from_count + $number[$i]; if ($divide >= $to_count) { $number[$newlen++] = (int)($divide / $to_count); $divide = $divide % $to_count; } elseif ($newlen > 0) { $number[$newlen++] = 0; } } $length = $newlen; $result = $tobase{$divide} . $result; // Divide is basically $numstring % $to_count (i.e. the new character) } while ($newlen != 0); return $result; } $HEX = "0123456789ABCDEF"; $DEC = "0123456789"; print custombase_convert_big ("FFFFFF", $HEX, $DEC); // Prints "16777215" $BIN = "01"; $ASCII = ""; for ($i = 0; $i < 256; $i++) { $ASCII .= chr($i); } $msg = "0100100101110100001000000101011101101111011100100110101101110011"; print custombase_convert_big($msg, $BIN, $ASCII); // Prints "It Works" ?>

« previous php.notes (#181170) next »