PHP failed echo

6

Because this:

echo 1 ^ 2;

is equal to 3?

And because this:

echo 0x33, ' birds sit on ', 022, ' trees.';

It looks like this: "51 birds sit on 18 trees"?

    
asked by anonymous 24.10.2017 / 20:49

3 answers

12
  

Why 1^2 = 3 ?

Because the ^ operator is a bitwise operator that performs the XOR operation between the operands. If we imagine the binary representations of numbers (considering only 2 bits):

1 = 01
2 = 10

Doing XOR bit by bit we have:

1 ^ 2 = 01 ^ 10 = (0 xor 1) (1 xor 0) = 11

That is, 1^2 results in the binary number 11, which is the number 3 in decimal.

  

Why the message "51 birds sit on 18 trees"?

Because the 0x33 value is a hexadecimal representation of the number 51 in decimal, just as the 022 value is the octal representation of the decimal number.

Related

What are Decimal, Hexadecimal, and Octal Notation Numbers?

What practical use of bitwise operators in PHP?

Official Documentation: Bitwise Operators

    
24.10.2017 / 20:59
2

Example:

<?php
// 00001010
$a = 10;
// 01101001
$b = 105;

$c = $a ^ $b;
#   01101001
# & 00001010
# = 01100011

// Exibe 99 Na tela
// 01100011
echo $c;
?>

Then echo 1 ^ 2 is:

1 = 01
2 = 10
    11 = 3

As the rray said:

  

On the second code, 0x33 is hexadecimal for 51 and 022 is octal   to 18.

Source: link

    
24.10.2017 / 21:02
2

First of all, the ^ sign in php is part of the bitwise operators. In case the ^ is XOR (exclusive OR), bits that are active in $a or $b , but not both, are enabled.

Then

1 ^ 2 = 0001 ^ 0010 = 0011 = 3

0x33 is the hex representation of 51.

E

022 is octal for 18.

    
24.10.2017 / 20:59