Forum Moderators: coopster
I want to pass one parameter (a sum of numbers ie: 2+4+8+16+32+64) and parse the number to determine if any given number (Are these are base2 numbers?) is found in the sum. Say you pass a number (4+8+64) that triggers 3 different options in the function.
This function will parse the number but is there a faster or more compact method to do the same?
Function isOption($pn_value, $pn_sum)
{
// verify that $pn_value can be in $pn_sum
// returns true/false
// first # is 2 then double to increase (ie: 2, 4, 8, 16, 32...)
// maximum sum = 16384
$ln_control_sum = 16384;
$ln_sum = $pn_sum;
while( $ln_sum >= 1 )
{
if( $ln_sum >= $ln_control_sum )
{
$ln_sum = $ln_sum - $ln_control_sum;
if( $pn_value = $ln_control_sum ) return True;
}
$ln_control_sum = $ln_control_sum / 2;
}
return False;
}
Any ideas or comments would be welcomed.
You have a series that is basically 2^x that goes
1 2 4 8 16 32 64 ...
if you have 2 + 64 = 66, then options 2 and 7 are set, like file permissions. So given 37, you want to know whether option 2 is set.
$x = term to test - is it an option set in the total/
$y = sum
if ($y == ($y & $z))
{
echo "Y is set";
}
For example
$x = 2;
$y = 66;
$x & $y = 2 = bitwise and = $x
You woudl have to figure out how to make this work for the series of options that you're interested in, but you could, for example, just have an array of options
$options = array(1, 2, 4, 8, 16);
And then walk through the array.
This type of parameter is something I used many years ago when accessing various Windows features. As in your example one would pass a 66 as the parameter which would trigger effects based on both 2 and 64. Like 2 might be a "OK" button and 64 might be a "Cancel" button so both buttons would be displayed in the Windows window.
I want to do the same here in PHP.
You said "if ($y == ($y & $z))" but did you mean "if ($y == ($y & $x))" (x rather than z)?
Where did you get "So given 37"?
if( isOption(2, 66) ) would return true since 2 is in 66.