Home >Backend Development >PHP Problem >How to use ^ and & in bitwise operators
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).
^: 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 .= '我有'.$v.'的权力<br>'; } 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!