xor operator

Tags:

Xor operator can be used to swap variables. For example,


$a = 11
$b = 22

$a = $a xor $b
$b = $b xor $a
$a = $a xor $b

echo $a
echo $b

This will print:

22
11

The reason is that applying ‘xor $some_var’ twice gives the original value, i.e., $a is assigned ($a xor $b) xor ($b xor ($a xor $b)) = ($a xor $b) xor ($a) = $a xor $b xor $a = $b. By depending on xor operation, you can save one temporary variable which is usually required in swap operation.

In a simple application like personal diary, xor operator can be used as a navie encryption method. Suppose that a diary application requires its user to input a password. Then, the program may save $content xor $password to a file. When loading previously written diary, user input password. Then the program read ($content xor $password) and apply xor $password to it. Then the result equals ($content xor $password) xor $password = $content.

Most important drawback of this type of encryption lies in the fact that whether the password is correct or not can’t be decided while loading the data. If a user input wrong password, the program will simply show broken characters on screen.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *