I've got the following code:
print "\n1 & 11\n";
var_dump(1 & 11);
print "\n 2 & 222\n";
var_dump(2 & 222);
Why is the first result 1 ? And why is the second result 2?
The PHP Web site says that 2 & 222
(for example) should give me back a boolean value:
For example, $a & $b == true evaluates the equivalency then the bitwise and; while ($a & $b) == true evaluates the bitwise and then the equivalency."
I don't get it, how can 2 & 222
be 2
?
&
does a bitwise AND
. That is, it does an AND
operation on all the bits of the input.
In binary:
2 = 0000000010
222 = 1011011110
2 & 222 = 0000000010 ( = 2)
Do not confuse &
with &&
. &
does a bitwise AND
while &&
does a logical AND
.
2 && 222 = true
2 & 222 = 2
As for 1 & 11
1 = 0001
11 = 1011
1 & 11 = 0001 ( = 1)
So, 1 & 11 = 1
Further reading:
http://en.wikipedia.org/wiki/Binary_and#AND
http://en.wikipedia.org/wiki/AND_gate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With