Full lesson
Explore the full explanation, examples, and visuals at your own pace.
Same number, binary view
Bitwise operators work on each bit separately. A bit is a single binary digit, a 0 or a 1, and binary is just numbers written with those digits. Here, 12 is 1100 and 10 is 1010. Line them up, and every column gets handled on its own.
a = 12 # binary 1100
b = 10 # binary 1010
# 1 1 0 0 <- a
# 1 0 1 0 <- b
# | | | |
# each column handled on its ownThe three column rules
Each operator is a tiny decision made on one column of two bits. Take a 1 and a 0. AND gives 0, because both must be 1. OR gives 1, because either one is enough. XOR gives 1, because exactly one is 1.
- AND &: 1 only if both are 1
- OR |: 1 if either is 1
- XOR ^: 1 if exactly one is 1
Applying the rules to 12 and 10
Line up 1100 over 1010. For AND, only the leftmost column has two ones, so we get 1000, which is 8. For OR, any column with a one wins, giving 1110, or 14. For XOR, the columns that differ light up: 0110, which is 6. Same columns, different rule.
a = 12 # 1100
b = 10 # 1010
print(a & b) # 1000 -> 8
print(a | b) # 1110 -> 14
print(a ^ b) # 0110 -> 6Shifts move bits; NOT flips them
Shifts slide every bit sideways. Shifting 12 left by one gives 11000, which is 24, so it doubles. Shifting right by one drops the last bit and gives 0110, which is 6. NOT flips every bit, not just four, and Python stores negatives in two's complement, so ~12 becomes minus 13.
a = 12 # 1100
print(a << 1) # 11000 -> 24
print(a >> 1) # 0110 -> 6
print(~a) # -13 (every bit flipped)Checking one permission flag
Here's a practical use. One number can store several yes-or-no flags, one per bit. The flags value is 0110. A mask is a number with a one only in the column you care about, here 0100. AND keeps just that column. The result is 0100, nonzero, so write is allowed.
Line up the bits; each column gets its own tiny decision.
Line up the bits; each column gets its own tiny decision. So before you predict any bitwise result, write the numbers in binary on paper first.