Home > Article > Backend Development > [PHP] Basic use of bitwise AND & or | XOR ^
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
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)
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
[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)
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!