Home  >  Article  >  Backend Development  >  How to use ^ and & in bitwise operators

How to use ^ and & in bitwise operators

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-07-26 16:17:322554browse

Bit operations are unary and binary operations on bit patterns or binary numbers in programming. On many older microprocessors, bitwise operations are slightly faster than addition and subtraction, and generally bitwise operations are much faster than multiplication and division. In modern architectures, bitwise operations often operate at the same speed as addition (still faster than multiplication).

How to use ^ and & in bitwise operators

^: Bitwise XOR. Convert the values ​​into binary and compare them. As long as one of the same positions is 1, the result of that position is 1, otherwise it is 0. Examples are as follows:

$a=1;//二进制为00001
$b=2;//二进制为00010
echo $a^$b;// 00011 就是3,因此输出3

&: bitwise AND. Convert the values ​​into binary and compare them. If only two of the same positions are all 1, the result of that position is 1, otherwise it is 0. For example:

$a=1;//二进制为00001
$b=2;//二进制为00010
$c=3;//二进制为00011

echo $a&$b;// 00000 就是0,因此输出0
echo $a&$c;// 00001 就是1,因此输出1
echo $b&$c;// 00010 就是2,因此输出2

The return value after bitwise & is mainly used to determine whether $a exists in $c, so there are many permission usages. For example,

$my_privilege = 15; // 1+2+4+8 拥有全部权限
$Pri = '';
$privilege_arr = array(8=>'增', 4=>'删',2=>'改',1=>'查');
foreach($privilege_arr as $k =>$v){
    $k & $my_privilege && $Pri .= &#39;我有&#39;.$v.&#39;的权力<br>&#39;;
}
echo $Pri;//输出结果

recommends learning: php video tutorial

The above is the detailed content of How to use ^ and & in bitwise operators. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete