note 102403 modified in language.operators.bitwise by danbrown

[email protected] Sat, 12 Feb 2011 09:59:31 -0800
Newsgroups php.notes
Message-ID <[email protected]>
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