PHP教程之变量互换_PHP教程
程序员文章站
2024-02-05 17:07:16
...
Attributed to Solomon W. Golomb; a method for swapping the values of two integer variables without using an intermediate variable (you can tell this dates from the Elder Days, when variables were expensive!). Thanks to PHP's syntax it's also a one-liner.
$a^=$b^=$a^=$b;
Okay, here's how it goes (yeah, like I need to make content-free posts just for the sake of an increment...).
First, simplify the line; noting that ^= is right-associative, which means that in that line the rightmost operator is evaluated first, that the assignment operators also return the value that they assign to their lvalue, and that foo^=bar is shorthand for foo=foo^bar:
Code:
Recall what ^ does. Takes each pair of corresponding bits from its arguments (the internal binary representation of its arguments, that is), and xors them together to produce the corresponding bit of the result ("corresponding" means that the first bits of both arguments produce the first bit of the result, the second bits of both arguments produce the second bit of the result, and so on. This is why, as BuzzLY noted, it's important that both variables are the same size - demons probably start flying out of your nose if one of them runs out of bits to xor before the other. So to figure out what ^ does to a pair of variables, we only need to recap what it does to single bits
$a^=$b^=$a^=$b;
Okay, here's how it goes (yeah, like I need to make content-free posts just for the sake of an increment...).
First, simplify the line; noting that ^= is right-associative, which means that in that line the rightmost operator is evaluated first, that the assignment operators also return the value that they assign to their lvalue, and that foo^=bar is shorthand for foo=foo^bar:
Code:
$a^=$b^=$a^=$b;
$a^=($b^=($a^=$b));
$a=$a^b;
$a^=($b^=$a);
$a=$a^$b;
$b=$b^$a;
$a=$a^$b;
Recall what ^ does. Takes each pair of corresponding bits from its arguments (the internal binary representation of its arguments, that is), and xors them together to produce the corresponding bit of the result ("corresponding" means that the first bits of both arguments produce the first bit of the result, the second bits of both arguments produce the second bit of the result, and so on. This is why, as BuzzLY noted, it's important that both variables are the same size - demons probably start flying out of your nose if one of them runs out of bits to xor before the other. So to figure out what ^ does to a pair of variables, we only need to recap what it does to single bits
推荐阅读
-
PHP与Perl兼容的正则表达式_PHP教程
-
php学习笔记 [预定义数组(超全局数组)]_PHP教程
-
Call to undefined function imagettftext()解决方法,calltoundefined_PHP教程
-
PHP教程之变量互换_PHP教程
-
php 使用openssl_verify验证签名实例程序_PHP教程
-
php遍历目录,生成目录下每个文件的md5值并写入到结果文件中_PHP教程
-
PHP 头像上传,php头像上传_PHP教程
-
php菜鸟入门视频教程上载_第101讲到112讲_张恩民老师
-
php中设置session过期时间方法_PHP教程
-
ThinkPHP 分页函数的改造_PHP教程