note 55204 added to function.base-convert
| From: | rithiur at mbnet dot fi | Date: | Wed, 27 Jul 2005 15:23:38 +0000 |
| Subject: | note 55204 added to function.base-convert | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-92566@lists.php.net to get a copy of this message | ||
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"
?>
----
Manual Page -- http://www.php.net/manual/en/function.base-convert.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+55204
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+55204&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+55204&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+55204&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+55204&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+55204&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+55204&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+55204&report=yes
Search -- http://master.php.net/manage/user-notes.php