pythonbitwise-operatorsampersandtilde

Bitwise operators:- Ball, carrot, ampersand, tilde


I want the step by step explanation of the following code:

print(1 | 0 ^ 1 & ~0)

I tried with the output bit (output with first and second bit) and got the answer as 0. The tilde function got me hooked up for some time I found it a bit hard. The answer is 1.


Solution

  • First you must understand what each operator does

    | - Bitwise OR: Returns True (1) if either of its operands is 1. e.g.

    1 | 0 == True

    & - Bitwise AND: Returns True if both of its operands are 1. e.g.

    0 & 1 == False

    ^ - Bitwise XOR: Returns True if only one of its operands is 1. e.g.

    0 ^ 1 == True

    ~ - Bitwise NOT: Flips the bit of its operand.

    edit: As noted by Daniel Martin, In Python specifically, it flips all of the bits of an arbitrary integer. The formula would be ~x == -x - 1 e.g.

    ~0 == -1

    Then you must understand the order of bitwise operations

    In order of precedence:

    ~ -> & -> ^ -> |

    Solving the expression in that order

    1. 1 | 0 ^ 1 & ~0 == 1 | 0 ^ 1 & -1 - ~ is applied first
    2. 1 | 0 ^ 1 & -1 == 1 | 0 ^ 1 - & is applied second
    3. 1 | 0 ^ 1 == 1 | 1 - ^ is applied third
    4. 1 | 1 == 1 - | is applied last