php – 交换两个变量的XOR技巧如何真正起作用?

我刚刚遇到这段代码,用于在PHP中交换两个变量的值:

<?php
$a = ‘bar’;
$b = ‘foo’;

$a = $a ^ $b;
$b = $a ^ $b;
$a = $a ^ $b;

echo $a . $b;

我理解二进制的概念;这总是适用于字符串吗?怎么样?

解决方法:

PHP通过将按位运算符单独应用于每个字符来将其应用于字符串.

PHP: Bitwise Operators

Be aware of data type conversions. If both the left-hand and right-hand parameters are strings, the bitwise operator will operate on the characters’ ASCII values.

如果两个字符串具有相同的字符数,或者更准确地说是相同的字节数,则这将起作用.如果上面的引用非常精确,那么它可能仅适用于仅ASCII字符串.

上一篇:javascript-“〜”运算符在此脚本中做什么?


下一篇:c – ostream deferencing operator <<