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.
|
- 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
In order of precedence:
~
-> &
-> ^
-> |
1 | 0 ^ 1 & ~0 == 1 | 0 ^ 1 & -1
- ~
is applied first1 | 0 ^ 1 & -1 == 1 | 0 ^ 1
- &
is applied second1 | 0 ^ 1 == 1 | 1
- ^
is applied third1 | 1 == 1
- |
is applied last