Masks and Power of Two
Bit Manipulation: lesson 4 of 5
One shifted bit is a key to any position you like.
Lesson 4 of 5 · 5 min
Masks and Power of Two
Step 1 of 10
11 is 0b1011. To touch one lane without disturbing the others, you need a key for that lane.
The Idea
A mask is a number whose 1s mark the lanes you care about. 1 << i builds the mask for a single position.
From there: OR sets a bit, AND with the inverted mask clears it, XOR flips it, and shifting right then ANDing 1 reads it. n & (n - 1) == 0 says n has at most one bit set.
Real-World Example
Feature flags ship as one integer. "Dark mode on, beta search off" is a single OR and a single AND — one field in the database instead of forty boolean columns, and the check costs one instruction on the request path.
The Code
def get_bit(x, i): return (x >> i) & 1
def set_bit(x, i): return x | (1 << i)
def clear_bit(x, i): return x & ~(1 << i)
def flip_bit(x, i): return x ^ (1 << i)
x = 0b1011 # 11
print(get_bit(x, 2)) # 0
print(bin(set_bit(x, 2))) # 0b1111
print(bin(clear_bit(x, 0))) # 0b1010
print(bin(flip_bit(x, 3))) # 0b11
def is_power_of_two(n):
return n > 0 and n & (n - 1) == 0 # exactly one bit set
print(is_power_of_two(16), is_power_of_two(12)) # True FalseYour turn
What does this print?
x = 0b1010
x = x | (1 << 0)
x = x & ~(1 << 3)
print(bin(x))Mini quiz
1 / 3