This Bitwise Operators lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
Bitwise operators look at the bits of integers. & keeps bits that are set in both numbers. | keeps bits set in either number. << shifts bits left.
Everyday application code rarely needs them. They show up in flags, masks, and binary formats.
Example 1: Start here
1 << 3 is 8. The bits of 1 moved three places left.
print(5 & 3) # this operator works on the bits of the number
print(5 | 2) # this operator works on the bits of the number
print(1 << 3) # a comparison is True or False
Example 2: And, or, xor
These operators work on the bits of the numbers. 5 is 101 in binary and 3 is 011.
print(5 & 3) # this operator works on the bits of the number
print(5 | 3) # this operator works on the bits of the number
print(5 ^ 3) # this operator works on the bits of the number
Example 3: Shift left
A left shift moves the bits and multiplies by two for each step. 1 shifted three times is 8.
print(1 << 3) # a comparison is True or False
Example 4: A simple flag
Flags use bits so several yes-or-no choices fit in one number.
READ = 1 # a whole number
WRITE = 2 # a whole number
mode = READ | WRITE # the bits combined into one number
print(mode & READ) # this operator works on the bits of the number
