php语法这些做什么用的? '^'和'|'

时间:2012-05-09 21:38:19

标签: php syntax operands

在php中,以下操作数如何工作?

^ |

e.g。 $a = 11; $b = 7; echo $a ^ $b;

输出12

    $a =    11;
$b =    7;
echo $a | $b;

输出15

我不确定为什么在每种情况下。有人可以解释一下吗?

3 个答案:

答案 0 :(得分:4)

这些是按位XOROR

$a = 11; // 1011
$b =  7; // 0111

XOR $a$b中的每个位变为1,相同的位变为0

$a ^ $b: // 1100 = 12

OR 1$a$b的每个位都变为1,在本例中为所有位。

$a | $b: // 1111 = 15

还有一个 AND 等价物:$a & $b: // 0011 = 3

A full list of PHP's bitwise operators .

答案 1 :(得分:3)

他们是按位运算符。

http://php.net/manual/en/language.operators.bitwise.php

基本上这些用于二进制数据。这些经常用于在一个整数内组合一系列标志。例如,如果我有两个标志:

FLAG1 = (binary)'1' = (integer)1
FLAG2 = (binary)'10' = (integer)2

我可以使用按位运算符组合两者:

$combined_flags = FLAG1 | FLAG2 = (binary)'11' = (integer)3

然后我可以检查其中一个标志是否也使用按位运算符设置:

if ($combined_flags & FLAG1) echo 'flag 1 is set to true.';

答案 2 :(得分:0)

它们是按位运算符,这意味着它们以二进制数运算。

111011二进制,70111

^XOR。对于两个值中的每个位,如果它们不同,则返回1.

11 ^ 7 = 1011 ^ 0111 = 1100 = 12

|OR。对于两个值中的每个位,如果至少有一个为1,则返回1.

11 | 7 = 1011 | 0111 = 1111 = 15

更多信息:http://php.net/manual/en/language.operators.bitwise.php