Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 17 / Topic 20 of 20

Bit manipulation

An integer is a row of bits — tiny on/off switches — and Python's & | ^ ~ << >> operate on all of them at once. Two habits cover most real uses: packing many yes/no flags into one number with masks, and exploiting XOR's self-cancelling (x ^ x == 0) to find the odd one out. Think of a fuse box: one strip of switches, and you can read, flip or test any single switch without touching the rest.

Want to... Write Why it works
set bit b flags |= b OR turns bits on
clear bit b flags &= ~b AND with the inverted mask turns it off
test bit b bool(flags & b) AND keeps only that bit
multiply/divide by 2ᵏ x << k, x >> k shifting moves every bit k places
READ, WRITE, ADMIN = 1 << 0, 1 << 1, 1 << 2   # 0b001, 0b010, 0b100

perms = READ | WRITE
print(bin(perms))              # 0b11
print(bool(perms & ADMIN))     # False
perms |= ADMIN                 # grant
perms &= ~WRITE                # revoke
print(bin(perms))              # 0b101

XOR cancels pairs — fold a list together and only the unpaired value survives:

scans = [7, 3, 11, 3, 7]
left_on = 0
for scanner_id in scans:
    left_on ^= scanner_id
print(left_on)                 # 11: every paired ID cancelled itself

29 == 0b11101 has (29).bit_count() == 4 set bits (bit_count() arrived in Python 3.10; bin(n).count("1") works anywhere).

Real-world example: Unix file permissions (rwx = three bits), feature flags in a config service, and "which of 8 sensors tripped?" status bytes from hardware are all this exact masks pattern.

⚠️ ~b in Python is NOT "the other 31 bits flipped" — integers are unbounded, so ~2 == -3. Inside flags &= ~b that is exactly what you want; printed on its own it surprises people. And remember ^ is XOR, not exponent — powers are **.

Practice: set/clear/test permission masks; find the single unpaired number with XOR; count set bits, and generate all subsets of a small set by counting masks from 0 to 2ⁿ−1 (a neat bridge back to backtracking).

Practice on LeetCode - start here: Single Number · Number of 1 Bits · Counting Bits · Missing Number · Reverse Bits

Show the full practice list (8 more problems)

Core practice - gentler first:

Stretch - tougher; come back once the core feels comfortable:

Full program: examples/20_bit_manipulation.py.

Exercise 20: Bit manipulation — permissions and the unpaired ID

Scenario: A device stores its permissions in one integer (READ=1, WRITE=2, ADMIN=4), and a warehouse scan log lists every scanner ID twice — except the one someone forgot to switch off. What to do: Starting from perms = READ: grant WRITE with |=, test ADMIN with &, revoke READ with &= ~READ, printing bin(perms) after each change. Then fold SCANS = [5, 9, 2, 9, 5] together with ^= to find the unpaired scanner.

Sample output:

after granting WRITE: 0b11
has ADMIN: False
after revoking READ: 0b10
unpaired scanner: 2

💡 Hint: x ^ x = 0 and x ^ 0 = x, so every paired ID cancels itself no matter the order.

Show the solution to Exercise 20
"""Exercise 20: Bit manipulation - permissions and the unpaired ID.

The permission field is one integer; |, & and ~ set, test and clear
single bits. XOR cancels pairs, so folding every ID together leaves
exactly the one that appears once.

Run:   python ex20.py   (macOS/Linux: python3 ex20.py)
"""

READ, WRITE, ADMIN = 1, 2, 4
SCANS = [5, 9, 2, 9, 5]


def main() -> None:
    perms = READ
    perms |= WRITE                      # grant WRITE
    print(f"after granting WRITE: {bin(perms)}")
    print(f"has ADMIN: {bool(perms & ADMIN)}")
    perms &= ~READ                      # revoke READ
    print(f"after revoking READ: {bin(perms)}")

    unpaired = 0
    for scanner_id in SCANS:
        unpaired ^= scanner_id
    print(f"unpaired scanner: {unpaired}")


if __name__ == "__main__":
    main()

Search the guide