When should I use a bitwise operator?

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

  • Difference between & and && in PHP

  • Reference - What does this symbol mean in PHP?

  • 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.


    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
    }
    

    Bitwise is useful for things in PHP just like anything else.

    How about a value that can have multiple states turned on at the same time (perhaps permissions)?

    <?php
    
    # must double them like this for it to work.
    const STATE_FOO = 1;
    const STATE_BAR = 2;
    const STATE_FEZ = 4;
    const STATE_BAZ = 8;
    
    # set state to foo and fez
    $state = STATE_FOO | STATE_FEZ;
    
    echo "What's the value: $staten";
    echo "Is foo state on? ".(bool)($state & STATE_FOO)."n";
    echo "Is bar state on? ".(bool)($state & STATE_BAR)."n";
    echo "Is fez state on? ".(bool)($state & STATE_FEZ)."n";
    echo "Is baz state on? ".(bool)($state & STATE_BAZ)."n";
    echo "Is foo and fez state on? ".($state == (STATE_FOO | STATE_FEZ))."n";
    

    In most cases, you'll probably want to use logical operators. They're used for combining logical conditions, generally to control program flow, eg ($isAlive && $wantsToEat) .

    Bitwise operators are used when you want to perform operations on a bit-by-bit basis on the underlying binary representations of integers. eg (5 & 3) == 7 . As others have suggested, there's usually not a lot of call for this in the sort of application that tends to get written in PHP (although there is in lower-level languages, like C).

    链接地址: http://www.djcxy.com/p/1706.html

    上一篇: 有没有必要在对象前面使用&符号?

    下一篇: 什么时候应该使用按位运算符?