note 102403 modified in language.operators.bitwise by danbrown

From: Date: Sat, 12 Feb 2011 17:59:31 +0000
Subject: note 102403 modified in language.operators.bitwise by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-176931@lists.php.net to get a copy of this message
More referencing this for myself than anything... if you need to iterate through every possible binary combination where $n number of flags are set to 1 in a mask of $bits length: <?php echo masksOf(3,10); function masksOf($n,$bits) { $u = pow(2,$bits)-1; //start value, full flags on. $masks = array(); while ($u>0) { $z = numflags($u); if ($z==$n) array_push($masks,$u); $u--; } return ($masks); } function numflags($n) { $k = 0; while ($n) { $k += $n & 1; $n = $n >> 1; } return ($k); // alternately: // $u = 0; // for ($k=1;$k<=$n;$k*=2) { // $u+=($n&$k?1:0); // } // return ($u); } ?> --was-- More referencing this for myself than anything... if you need to iterate through every possible binary combination where $n number of flags are set to 1 in a mask of $bits length: echo masksOf(3,10); function masksOf($n,$bits) { $u = pow(2,$bits)-1; //start value, full flags on. $masks = array(); while ($u>0) { $z = numflags($u); if ($z==$n) array_push($masks,$u); $u--; } return ($masks); } function numflags($n) { $k = 0; while ($n) { $k += $n & 1; $n = $n >> 1; } return ($k); // alternately: // $u = 0; // for ($k=1;$k<=$n;$k*=2) { // $u+=($n&$k?1:0); // } // return ($u); } http://php.net/manual/en/language.operators.bitwise.php

« previous php.notes (#176931) next »