Jump to content

Use of the Expression ($var & 1)


iwato

Recommended Posts

QUESTION: What is being compared in the expression ($var & 1), and why does it work in the identification of odd and even numbers?BACKGROUND: These are two callback functions used with the array_filter( ) function to separate odd from even numbers.

<?php	function odd($var) {		return($var & 1);	}	function even($var) {		return(!($var & 1));	}?>

Roddy

Link to comment
Share on other sites

& is a bitwise AND on $var.If $var is a decimal 4, it's a binary 100. 100 & 1 is 100, because the right most digit is a 0 in $var - and 0 & 1 is 0, thus, 4 is even.
So, you appear to be saying that only the right-most binary digit of each number is compared?Is this always the case with & operator, or does it vary with context? If it varies with context could you give an example?Roddy
Link to comment
Share on other sites

& 100 would compare the left-most binary digit.http://en.wikipedia.org/wiki/Bitwise_operationIf you are doing math with even numbers, especially divisible by 2, bitwise operations can be much faster than using arithmetic.$var >> 1 (shift $var right 1 bit) is the same as $var / 2, but may execute much more quickly. The reason I say may is that some compilers will optimize the / and use >>.

Link to comment
Share on other sites

Basically, with bitwise operators, every digit of the binary representation of the left number is compared to the corresponding digit in the binary representation in the right number.So, to keep up with the "4" example:100&001=000And of course, you should know by now that "000" is the binary representation of "0", which is evaluated to a boolean false (though the odd() function don't cast explicitly).As to what happens with what values with each bitwise operations, see not only the article wirehopper mentioned, but I'd also suggest truth tables. Replacing "F" with "0" and "T" with "1" shows you the situation.

Link to comment
Share on other sites

  • 4 weeks later...
Basically, with bitwise operators, every digit of the binary representation of the left number is compared to the corresponding digit in the binary representation in the right number....As to what happens with what values with each bitwise operations, see not only the article wirehopper mentioned, but I'd also suggest truth tables....
I know that it is a little belated, but still I would like to thank you and wirehopper for your great help. Together you made it very clear what I needed to know in order to understand what I did not.Roddy
Link to comment
Share on other sites

  • 2 months later...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...