Monday, 4 September 2017

php - When should I use a bitwise operator?




I read the following questions, and I understand the differences between bitwise and logical.





However, none of them explains when I should use bitwise or logical.



When should I use bitwise operators rather than logical ones and vice versa?



In which situation do I need to compare bit by bit?




I am not asking about the differences, but I am asking the situation when you need to use bitwise operators.


Answer



Bitwise | and & and logical || and && are totally different.



Bitwise operators perform operations on the bits of two numbers and return the result. That means it's not a yes or no thing. If they're being used in conditional statements, they're often used as part of logical comparisons. For example:



if ($x & 2 == 2) {
// The 2^1 bit is set in the number $x
}



Logical operators compare two (or more) conditions/expressions and return true or false. You use them most commonly in conditional statements, like if and while. For example:



if ($either_this || $or_this) {
// Either expression was true
}

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...