note 25336 added to ref.bc

From: Date: Fri, 20 Sep 2002 01:27:03 +0000
Subject: note 25336 added to ref.bc
Groups: php.notes 
Request: Send a blank email to php-notes+get-37006@lists.php.net to get a copy of this message
A good use for BCMath functions: The functions below can convert a number in any base (from 2 to 256) to its decimal value and vice-versa. // convert a decimal value to any other base value function dec2base($dec,$base,$digits=FALSE) { if($base<2 or $base>256) die("Invalid Base: ".$base); bcscale(0); $value=""; if(!$digits) $digits=digits($base); while($dec>$base-1) { $rest=bcmod($dec,$base); $dec=bcdiv($dec,$base); $value=$digits[$rest].$value; } $value=$digits[intval($dec)].$value; return (string) $value; } // convert another base value to its decimal value function base2dec($value,$base,$digits=FALSE) { if($base<2 or $base>256) die("Invalid Base: ".$base); bcscale(0); if($base<37) $value=strtolower($value); if(!$digits) $digits=digits($base); $size=strlen($value); $dec="0"; for($loop=0;$loop<$size;$loop++) { $element=strpos($digits,$value[$loop]); $power=bcpow($base,$size-$loop-1); $dec=bcadd($dec,bcmul($element,$power)); } return (string) $dec; } function digits($base) { if($base>64) { $digits=""; for($loop=0;$loop<256;$loop++) { $digits.=chr($loop); } } else { $digits ="0123456789abcdefghijklmnopqrstuvwxyz"; $digits.="ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"; } $digits=substr($digits,0,$base); return (string) $digits; } The purpose of digits() function above is to supply the characters that will be used as digits for the base you want. NOTE: You can use any characters for that when you convert to another base, but when you convert again to the decimal base, you need to use the same characters or you will get another unexpected result. -- http://www.php.net/manual/en/ref.bc.php http://master.php.net/manage/user-notes.php?action=edit+25336 http://master.php.net/manage/user-notes.php?action=delete+25336 http://master.php.net/manage/user-notes.php?action=reject+25336

« previous php.notes (#37006) next »