交换两个变量的XOR技巧如何真正作用于字符串? [英] How does the XOR trick to swap two variables really work on a string?

查看:91
本文介绍了交换两个变量的XOR技巧如何真正作用于字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是碰到了这段代码片段,用于交换PHP中两个变量的值:

I just ran across this snippet of code for swapping the values of two variables in PHP:

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

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

echo $a . $b;

我理解二进制的概念;这总是在字符串上工作吗?怎么样?

I understand the concept in binary; does this always work on strings? How?

推荐答案

PHP通过将逐位运算符分别应用于每个字符,将按位运算符应用于字符串.

PHP applies bitwise operators to strings by applying it to each character individually.

PHP:按位运算符:

请注意数据类型转换.如果左侧和右侧参数都是字符串,则按位运算符将对字符的ASCII值进行运算.

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的字符串.

This will work if both strings have the same number of characters, or more precisely the same number of bytes. If the above quote is really precise, then it may only work for ASCII-only strings.

这篇关于交换两个变量的XOR技巧如何真正作用于字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆