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

How to use ^ and & in bitwise operators

醉折花枝作酒筹
Release: 2023-03-11 19:50:01
forward
2577 people have browsed it

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
Copy after login

&: 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
Copy after login

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;//输出结果
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template