note 79072 added to function.bindec

From: Date: Fri, 09 Nov 2007 09:34:14 +0000
Subject: note 79072 added to function.bindec
Groups: php.notes 
Request: Send a blank email to php-notes+get-132144@lists.php.net to get a copy of this message
The "smartbindec" function I wrote below will convert any binary string (of a reasonable size) to decimal. It will use two's complement if the leftmost bit is 1, regardless of bit length. If you are getting unexpected negative answers, try zero-padding your strings with sprintf("%032s", $yourBitString). <?php function twoscomp($bin) { $out = ""; $mode = "init"; for($x = strlen($bin)-1; $x >= 0; $x--) { if ($mode != "init") $out = ($bin[$x] == "0" ? "1" : "0").$out; else { if($bin[$x] == "1") { $out = "1".$out; $mode = "invert"; } else $out = "0".$out; } } return $out; } function smartbindec($bin) { if($bin[0] == 1) return -1 * bindec(twoscomp($bin)); else return (int) bindec($bin); } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 207.225.190.135 ---- Manual Page -- http://www.php.net/manual/en/function.bindec.php Edit -- https://master.php.net/note/edit/79072 Del: integrated -- https://master.php.net/note/delete/79072/integrated Del: useless -- https://master.php.net/note/delete/79072/useless Del: bad code -- https://master.php.net/note/delete/79072/bad+code Del: spam -- https://master.php.net/note/delete/79072/spam Del: non-english -- https://master.php.net/note/delete/79072/non-english Del: in docs -- https://master.php.net/note/delete/79072/in+docs Del: other reasons-- https://master.php.net/note/delete/79072 Reject -- https://master.php.net/note/reject/79072 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#132144) next »