Possible Duplicate:
Reference – What does this symbol mean in PHP?
I am working on some legacy code where I came across the following function:
function is_odd($number) {
return $number & 1; // 0 = even, 1 = odd
}
I have never seen a method to check if a number is odd written like that before and am just trying to understand what they actually are doing.
&is a bitwise-and, it basically works so that for every bit that is1in both operands, it yields1in the resulting value and0for all other bits. If you convert any number to its bit representation, you quickly see that it’s the lowest bit that determines whether a number is even or odd, for example:The lowest bit (the one on the very right, also called the least significant bit) is 1 for every odd number and 0 for every even number. Doing
$n & 1will always yield0for every other bit than the lowest bit (because the number 1 only has one bit, you can imagine that the rest of the bits are left-padded with 0 to match the length of the other operand). So basically the operation boils down to comparing the lowest bit of the operands, and1 & 1is 1, all other combinations are 0. So basically when the$n & 1yields 1, it means the number is odd, otherwise it’s even.EDIT.
Here’s a few examples to demonstrate how the bitwise-and works for the example values I gave earlier, the number in the parenthesis is the original decimal number:
From this you can easily see that the result is only true when both operands’ right-most bits are 1.