What is & in return($var & 1) in PHP

Possible Duplicate:
Reference - What does this symbol mean in PHP?

When I was reading this php page, I was not sure what & is doing in $var & 1.

function odd($var)
{
    // returns whether the input integer is odd
    return($var & 1);
}

Is it returning a reference? I am not sure.

If you can explain it or direct me a php page, I will appreciate it.

Thanks in advance.


It's a bitwise-AND operation. All odd numbers have LSB (least significant bit set to 1), even numbers - 0.

So it simply "ANDs" two numbers together. For example, 5. It is represented as 101 in binary. 101 & 001 = 001 => true, so it is odd.


It is performing bitwise ANDing . That is a bitwise operator

$a & $b Bits that are set in both $a and $b are set.


In this case, return($var & 1); will do a bitwise AND against 0000....0001 returning 1 or 0 depending on the last bit of $var .

If the binary representation of a number ends in 0, it is even (in decimal).

If the binary representation of a number ends in 1, it is odd (in decimal).


& is the bitwise and operator. In this case it will return 1 if $var is odd, 0 if $var is even.

链接地址: http://www.djcxy.com/p/10218.html

上一篇: 在C#中使用通配符解析相对路径

下一篇: 什么是&PHP($ var&1)