note 44910 added to function.bindec

From: Date: Thu, 19 Aug 2004 21:43:03 +0000
Subject: note 44910 added to function.bindec
Groups: php.notes 
Request: Send a blank email to php-notes+get-74957@lists.php.net to get a copy of this message
i think a better method than the "shift-method" is my method ^^... here it comes: function convert2bin($string) { $finished=0; $base=1; if(preg_match("/[^0-9]/", $string)) { for($i=0; $string!=chr($i); $i++); $dec_nr=$i; } else $dec_nr=$string; while($dec_nr>$base) { $base=$base*2; if($base>$dec_nr) { $base=$base/2; break; } } while(!$finished) { if(($dec_nr-$base)>0) { $dec_nr=$dec_nr-$base; $bin_nr.=1; $base=$base/2; } elseif(($dec_nr-$base)<0) { $bin_nr.=0; $base=$base/2; } elseif(($dec_nr-$base)==0) { $bin_nr.=1; $finished=1; while($base>1) { $bin_nr.=0; $base=$base/2; } } } return $bin_nr; } ===================================================== if you want to reconvert it (from binary to string or integer) you can use this function: function reconvert($bin_nr) { $base=1; $dec_nr=0; $bin_nr=explode(",", preg_replace("/(.*),/", "$1", str_replace("1", "1,", str_replace("0", "0,", $bin_nr)))); for($i=1; $i<count($bin_nr); $i++) $base=$base*2; foreach($bin_nr as $key=>$bin_nr_bit) { if($bin_nr_bit==1) { $dec_nr+=$base; $base=$base/2; } if($bin_nr_bit==0) $base=$base/2; } return(array("string"=>chr($dec_nr), "int"=>$dec_nr)); } ---- Manual Page -- http://www.php.net/manual/en/function.bindec.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+44910 Delete -- http://master.php.net/manage/user-notes.php?action=delete+44910&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+44910&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#74957) next »