Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise operator in PHP

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 ?

like image 401
Polichism Avatar asked Feb 19 '23 10:02

Polichism


1 Answers

& 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

like image 72
xbonez Avatar answered Feb 26 '23 23:02

xbonez