Bitwise operator in PHP

I have 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 the second result 2?

The PHP website says 2 & 222 (for example) should return me a boolean:

For example, $ a and $ b == true evaluates equivalence, and then bitwise; and ($ a and $ b) == true evaluates bitwise and then equivalence. "

I do not understand how 2 & 222 be 2 ?

+4
source share
3 answers

In bits:

  • 01
  • ten
  • eleven

The & operator returns all bits equal to 1 in both numbers. So:

  • 1 and 2 → 01 and 10 → 00 == 0
  • 2 and 3 → 10 and 11 → 10 == 2
+3
source

& performs bitwise AND . That is, it performs an AND operation for all input bits.

In binary format:

 2 = 0000000010 222 = 1011011110 2 & 222 = 0000000010 ( = 2) 

Do not confuse & with && . & makes a bitwise AND , and && makes 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

+5
source

One ampersand is a bitwise and operator.
In the above quote, you are informed that you must know the priority of the operator when performing bit operations and comparisons. You might expect $a & $b == true check if certains bits are set to $ a, but this is equivalent

$ a and (int) ($ b == true)

Since you do not mix bit operations and comparison in var_dump(1&11); or var_dump(2 & 222); , this note should not bother you.
This is just bitwise and, as explained in https://en.wikipedia.org/wiki/Bitwise_operation#AND

see also:
http://docs.php.net/language.operators.precedence
http://docs.php.net/language.types.type-juggling

0
source

Source: https://habr.com/ru/post/1447438/


All Articles