Why 1 2 is 3 and why when I display 0x33 appears 51 and 022 appears 18?

Asked

Viewed 135 times

7

Because that:

echo 1 ^ 2;

is equal to 3?

And why that:

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

is equal to this: "51 Birds sit on 18 Trees" ?

3 answers

14


Why 1^2 = 3?

Because the operator ^ is a bit-by-bit operator that performs the XOR operation between operands. If we imagine the binary representations of the numbers (considering only 2 bits - minimum quantity to represent the two values):

1 = 01
2 = 10

Doing the bit-by-bit XOR we have:

1 ^ 2 = 0 1 ^ 1 0 = (0 xor 1) (1 xor 0) = 11
        ⌊_|___⌋─|───────┘         |
          ⌊_____⌋─────────────────┘

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

As message "51 Birds sit on 18 Trees"?

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

Related

What are Decimal, Hexadecimal and Octal notation numbers?

What is the practical use of bitwise operators in PHP?

Official documentation: Bit-to-bit operators (bitwise)

2

First case, the sign of ^ php is part of the bit-by-bit operators. In this case the ^ is XOR (Exclusive OR), Bits that are active in $a or in $b, but not in both, are activated.

So

1 ^ 2 = 0001 ^ 0010 = 0011 = 3

0x33 is the representation in hexa of 51.

And

022 is the octal for 18.

1

Example:

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

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

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

So echo 1 2 is:

1 = 01
2 = 10
    11 = 3

As the rab spoke:

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

Source: https://www.todoespacoonline.com/w/2014/06/operadores-bit-bit-em-php/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.