0
0
DSA Pythonprogramming

Set Clear Toggle a Specific Bit in DSA Python

Choose your learning style9 modes available
Mental Model
We change one specific bit in a number to 1, 0, or flip it without affecting other bits.
Analogy: Imagine a row of light switches where each switch controls one light. Setting a bit is like turning a specific switch on, clearing is turning it off, and toggling is flipping its current state.
Number bits: 0 0 1 0 1 1 0 1
Positions:  7 6 5 4 3 2 1 0
Toggle bit 3 -> flip the switch at position 3
Dry Run Walkthrough
Input: number = 45 (binary 00101101), bit position = 3
Goal: Set, clear, and toggle the bit at position 3 in the number 45
Step 1: Set bit 3 to 1 using OR with mask 1 << 3
00101101 (45) OR 00001000 (8) = 00101101 (45)
Why: Bit 3 is already 1, so setting it keeps the number unchanged
Step 2: Clear bit 3 to 0 using AND with inverse mask ~(1 << 3)
00101101 (45) AND 11110111 (247) = 00100101 (37)
Why: Clearing bit 3 turns that bit off, changing number from 45 to 37
Step 3: Toggle bit 3 using XOR with mask 1 << 3
00100101 (37) XOR 00001000 (8) = 00101101 (45)
Why: Toggling flips bit 3 back on, restoring number to 45
Result:
Final numbers after operations:
Set bit 3: 45 (00101101)
Clear bit 3: 37 (00100101)
Toggle bit 3: 45 (00101101)
Annotated Code
DSA Python
class BitManipulator:
    def __init__(self, number: int):
        self.number = number

    def set_bit(self, pos: int) -> int:
        # Set bit at pos to 1
        self.number |= (1 << pos)
        return self.number

    def clear_bit(self, pos: int) -> int:
        # Clear bit at pos to 0
        self.number &= ~(1 << pos)
        return self.number

    def toggle_bit(self, pos: int) -> int:
        # Flip bit at pos
        self.number ^= (1 << pos)
        return self.number

if __name__ == '__main__':
    num = 45  # binary 00101101
    pos = 3
    bm = BitManipulator(num)

    set_result = bm.set_bit(pos)
    print(f'Set bit {pos}: {set_result} ({set_result:08b})')

    clear_result = bm.clear_bit(pos)
    print(f'Clear bit {pos}: {clear_result} ({clear_result:08b})')

    toggle_result = bm.toggle_bit(pos)
    print(f'Toggle bit {pos}: {toggle_result} ({toggle_result:08b})')
self.number |= (1 << pos)
Set bit at position pos to 1 by OR with mask
self.number &= ~(1 << pos)
Clear bit at position pos to 0 by AND with inverted mask
self.number ^= (1 << pos)
Toggle bit at position pos by XOR with mask
OutputSuccess
Set bit 3: 45 (00101101) Clear bit 3: 37 (00100101) Toggle bit 3: 45 (00101101)
Complexity Analysis
Time: O(1) because bitwise operations take constant time regardless of number size
Space: O(1) because no extra space is needed beyond variables
vs Alternative: Using bitwise operations is much faster and simpler than converting to string or array and manipulating bits manually
Edge Cases
bit position is 0 (least significant bit)
Operations correctly affect the rightmost bit
DSA Python
self.number |= (1 << pos)
bit position is larger than number bit length
Bit is set/cleared/toggled at that position, effectively extending number's binary representation
DSA Python
self.number |= (1 << pos)
number is 0 initially
Setting bit turns number positive; clearing or toggling behaves as expected
DSA Python
self.number |= (1 << pos)
When to Use This Pattern
When you need to change a single bit in a number quickly, use set, clear, or toggle bit patterns because they directly manipulate bits without loops or conversions.
Common Mistakes
Mistake: Using AND instead of OR to set a bit, which can clear other bits
Fix: Use OR with mask to set a bit without affecting others
Mistake: Forgetting to invert mask when clearing a bit, causing wrong bits to be cleared
Fix: Use NOT (~) on mask before AND to clear only the target bit
Mistake: Using addition or subtraction to set or clear bits, which can cause errors
Fix: Use bitwise operators OR, AND, XOR for precise bit manipulation
Summary
It changes one specific bit in a number to 1, 0, or flips it.
Use it when you want to control individual bits efficiently in a number.
The key is to create a mask with 1 shifted to the bit position and use OR, AND with NOT, or XOR to set, clear, or toggle.