Bitwise operators are like logical operators but executed per bit rather than per boolean value.
// bitwise NOT ~: sets all unset bits and unsets all set bits
printf("%'06b", ~0b110110); // 001001
Bitwise AND &
: a bit is set only if it is set in both operands
printf("%'06b", 0b110101 & 0b011001); // 010001
Bitwise OR |
: a bit is set if it is set in either or both operands
printf("%'06b", 0b110101 | 0b011001); // 111101
Bitwise XOR ^
: a bit is set if it is set in one operand and not set in another operand, i.e. only if that bit is in different state in the two operands
printf("%'06b", 0b110101 ^ 0b011001); // 101100
These operators can be used to manipulate bitmasks. For example:
file_put_contents("file.log", LOCK_EX | FILE_APPEND);
Here, the |
operator is used to combine the two bitmasks. Although \\+
has the same effect, |
emphasizes that you are combining bitmasks, not adding two normal scalar integers.
class Foo{
const OPTION_A = 1;
const OPTION_B = 2;
const OPTION_C = 4;
const OPTION_A = 8;
private $options = self::OPTION_A | self::OPTION_C;
public function toggleOption(int $option){
$this->options ^= $option;
}
public function enable(int $option){
$this->options |= $option; // enable $option regardless of its original state
}
public function disable(int $option){
$this->options &= ~$option; // disable $option regardless of its original state,
// without affecting other bits
}
/** returns whether at least one of the options is enabled */
public function isOneEnabled(int $options) : bool{
return $this->options & $option !== 0;
// Use !== rather than >, because
// if $options is about a high bit, we may be handling a negative integer
}
/** returns whether all of the options are enabled */
public function areAllEnabled(int $options) : bool{
return ($this->options & $options) === $options;
// note the parentheses; beware the operator precedence
}
}
This example (assuming $option
always only contain one bit) uses:
^
operator to conveniently toggle bitmasks.|
operator to set a bit neglecting its original state or other bits~
operator to convert an integer with only one bit set into an integer with only one bit not set&
operator to unset a bit, using these properties of &
: