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.
First you must understand what each operator does
|- Bitwise OR: ReturnsTrue(1) if either of its operands is 1. e.g.1 | 0 == True&- Bitwise AND: ReturnsTrueif both of its operands are 1. e.g.0 & 1 == False^- Bitwise XOR: ReturnsTrueif 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 - 1e.g.~0 == -1Then you must understand the order of bitwise operations
In order of precedence:
~->&->^->|Solving the expression in that order
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