Bitwise Operators
Bitwise operators compare numbers in their binary form:
Bitwise Operators Table
main.py
# Operator | Name | Description | Example
# & | AND | Sets each bit to 1 if both bits are 1 | x & y
# | | OR | Sets each bit to 1 if one of two bits is 1 | x | y
# ^ | XOR | Sets each bit to 1 if only one of two bits is 1 | x ^ y
# ~ | NOT | Inverts all the bits | ~x
# << | Zero fill left shift | Shift left by pushing zeros in from the right and let the leftmost bits fall off | x << 2
# >> | Signed right shift | Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off | x >> 2
Examples
Example
& looks at each pair of bits. The result bit is 1 when both are 1, and 0 in every other case:
Prompt
Write a Python program that uses the bitwise AND operator (&) on the numbers 6 and 3, and prints the result.
Output: complete Python program
main.py
print(6 & 3)
Example
| looks at each pair of bits. The result bit is 1 when at least one of them is 1, and 0 otherwise:
Prompt
Write a Python program that uses the bitwise OR operator (|) on the numbers 6 and 3, and prints the result.
Output: complete Python program
main.py
print(6 | 3)
Example
^ looks at each pair of bits. The result bit is 1 when exactly one of them is 1. If they are both 1 or both 0, it is 0:
Prompt
Write a Python program that uses the bitwise XOR operator (^) on the numbers 6 and 3, and prints the result.
Output: complete Python program
main.py
print(6 ^ 3)