Loading lesson path
Bitwise operators are used to compare (binary) numbers:
&
Sets each bit to 1 if both bits are 1 x & y Try it » | OR Sets each bit to 1 if one of two bits is 1 x | y Try it » ^
Formula
Sets each bit to 1 if only one of two bits is 1 x ^ yTry it » ~
~x Try it » <<
Shift left by pushing zeros in from the right and let the leftmost bits fall off x << 2Try it » >>
Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off x >> 2Try it »
The & operator compares each bit and set it to 1 if both are 1, otherwise it is set to 0:
print(6 & 3)Then the & operator compares the bits and returns 0010, which is 2 in decimal.
The | operator compares each bit and set it to 1 if one or both is 1, otherwise it is set to 0:
print(6 | 3)Then the | operator compares the bits and returns 0111, which is 7 in decimal.
The ^ operator compares each bit and set it to 1 if only one is 1, otherwise (if both are 1 or both are 0) it is set to 0:
print(6 ^ 3)Formula
Then the ^ operator compares the bits and returns 0101, which is 5 in decimal.