4

I dont get how the following codes work?

function odd($var){
   return ($var & 1);
}
echo odd(4); /* returns and print 0 */
echo odd(5); /* returns and print 1 */

this function returns true if argument is an odd number and returns false if argument is an even number. How it works ?

partho
  • 1,101
  • 2
  • 21
  • 37

3 Answers3

4

Odd numbers in binary always have a least-significant bit (LSB) of 1. That is why your code

function odd($var){
   return ($var & 1);
}

returns true on odd numbers. Here are your examples from your question:

(decimal) 4 & 1 = (binary) 100 & 001 = (binary) 000 = (decimal) 0 = false
(decimal) 5 & 1 = (binary) 101 & 001 = (binary) 001 = (decimal) 1 = true

Another way to think of it is

    100 (decimal 4) - an even number 
AND 001 (decimal 1)  
  = 000 (decimal 0) - return false  

and

    101 (decimal 5) - an odd number  
AND 001 (decimal 1)  
  = 001 (decimal 1) - return true  
Drakes
  • 23,254
  • 3
  • 51
  • 94
4

bitwise comparison already says what it does: it compares the numbers bit by bit.

If we take 4 bits, the bit representation of 4 is: 0100. The bit representation of 5 is 0101. When we compare this with & (and), it returns the bits which are both set.

0100 & 0001 = 0000 (no bits are the same)
0101 & 0001 = 0001 (only Least Significant Bit (LSB) is 1)
Ronald Swets
  • 1,669
  • 10
  • 16
0

It is masking off all bits except 0. & is the and operator. And 1 is 000000000001 in binary. So it works as it is named.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41