[PHP] Basic use of bitwise AND & or | XOR ^

little bottle
Release: 2023-04-05 21:20:02
forward
3397 people have browsed it

Bitwise AND:
0&0=0; 0&1=0; 1&0=0; 1&1=1;
Bitwise OR:
0|0=0; 0|1=1; 1| 0=1; 1|1=1;
Bitwise XOR, on the basis of OR, 1 1 is also 0:
0^0=0; 0^1=1; 1^0=1; 1^1=0;

1. An int field that stores a decimal number, for example, 5
Then the number converted to binary is 101. I define it myself and count from left to right,
The first digit is 1, which means automatic forwarding of a certain function is on.
The second digit is 0, which means automatic deletion is off.
The third digit is 1, which means automatic saving is on.

2. Determine whether the third digit is Code to turn on automatic saving

($userStatus & pow(2,3-1))!=0
Copy after login

3.pow is an exponential expression function, 2 to the power of 2, converted to binary it is 0100, the bitwise AND of 0101 & 0100 is 0100 and the decimal system is 4, so it is not Equal to 0 is true
4. Set the value of a certain bit. If you want to set it to 1, the code is

$userStatus | pow(2,3-1)
Copy after login


The original value is 0001, and you want to set the third bit to 1,0001 | 0100 is 0101
5. Set a certain bit to 0, the code is

$userStatus ^ pow(2,3-1) 0101 ^ 0100 为0001
Copy after login

[Recommended course: PHP video tutorial]

function setStatus($source,$flag,$value){
        if (intval($value) == 1 || strcasecmp($value, 'on') == 0) {
            $value = 1;
        } else {
            $value = 0;
        }   

        $status = pow(2, $flag - 1); 
        $oldStat = (($source & $status) != 0); 
        if ($oldStat == $value) {
            return $source;
        }   
        if ($value) {
            $source |= $status;
        } else {
            $source ^= $status;
        }   
        return $source;
}
//001 转成 101 
var_dump(setStatus(1,3,'on'));//int(5)
//1101 转成 0101
var_dump(setStatus(13,4,0));//int(5) 
  
Copy after login

The above is the detailed content of [PHP] Basic use of bitwise AND & or | XOR ^. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!