Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How bitwise operator works [duplicate]

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 ?

like image 569
partho Avatar asked Feb 11 '23 01:02

partho


1 Answers

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  
like image 68
Drakes Avatar answered Feb 12 '23 16:02

Drakes