Bird
Raised Fist0
DSA Rustprogramming

Set Clear Toggle a Specific Bit in DSA Rust

Choose your learning style10 modes available
Mental Model
We change one specific bit in a number to 1, 0, or flip it without touching 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 0 0 1 0 1 0
Positions:  7 6 5 4 3 2 1 0
Toggle bit 3 -> changes bit at position 3 only
Dry Run Walkthrough
Input: number: 0b00001010 (decimal 10), operations: set bit 0, clear bit 3, toggle bit 2
Goal: Show how setting, clearing, and toggling a specific bit changes the number step-by-step
Step 1: Set bit 0 to 1
0 0 0 0 1 0 1 0 (binary 00001010) -> set bit 0 -> 0 0 0 0 1 0 1 1 (binary 00001011)
Why: Setting bit 0 ensures that bit is turned on regardless of previous value
Step 2: Clear bit 3 to 0
0 0 0 0 1 0 1 1 (binary 00001011) -> clear bit 3 -> 0 0 0 0 0 0 1 1 (binary 00000011)
Why: Clearing bit 3 turns off that bit regardless of previous value
Step 3: Toggle bit 2 (flip its value)
0 0 0 0 0 0 1 1 (binary 00000011) -> toggle bit 2 -> 0 0 0 0 0 1 1 1 (binary 00000111)
Why: Toggling flips bit 2 from 0 to 1, changing the number accordingly
Result:
Final binary: 00000111 -> decimal 7
Annotated Code
DSA Rust
fn set_bit(num: u8, pos: u8) -> u8 {
    num | (1 << pos) // turn bit at pos to 1
}

fn clear_bit(num: u8, pos: u8) -> u8 {
    num & !(1 << pos) // turn bit at pos to 0
}

fn toggle_bit(num: u8, pos: u8) -> u8 {
    num ^ (1 << pos) // flip bit at pos
}

fn main() {
    let mut num: u8 = 0b00001010; // 10 decimal
    println!("Initial: {:08b}", num);

    num = set_bit(num, 0);
    println!("After set bit 0: {:08b}", num);

    num = clear_bit(num, 3);
    println!("After clear bit 3: {:08b}", num);

    num = toggle_bit(num, 2);
    println!("After toggle bit 2: {:08b}", num);

    println!("Final decimal: {}", num);
}
num | (1 << pos) // turn bit at pos to 1
set bit by OR with mask having 1 at pos
num & !(1 << pos) // turn bit at pos to 0
clear bit by AND with mask having 0 at pos
num ^ (1 << pos) // flip bit at pos
toggle bit by XOR with mask having 1 at pos
num = set_bit(num, 0);
apply set bit operation
num = clear_bit(num, 3);
apply clear bit operation
num = toggle_bit(num, 2);
apply toggle bit operation
OutputSuccess
Initial: 00001010 After set bit 0: 00001011 After clear bit 3: 00000011 After toggle bit 2: 00000111 Final decimal: 7
Complexity Analysis
Time: O(1) because bitwise operations take constant time regardless of input size
Space: O(1) because no extra memory is used beyond fixed variables
vs Alternative: Using arithmetic or string conversions to manipulate bits is slower and more complex compared to direct bitwise operations
Edge Cases
position out of range (e.g., pos >= 8 for u8)
bit shift may overflow or produce unexpected results; code assumes valid positions
DSA Rust
No explicit guard; user must ensure pos < 8
number is zero
setting a bit turns that bit on; clearing or toggling behaves normally
DSA Rust
No special guard needed; bitwise ops handle zero correctly
toggling a bit twice returns original number
flip bit twice cancels out changes
DSA Rust
toggle_bit function logic
When to Use This Pattern
When you need to change a single bit in a number without affecting others, use set, clear, or toggle bit patterns because they efficiently manipulate bits with simple operations.
Common Mistakes
Mistake: Using addition or subtraction to set or clear bits instead of bitwise operators
Fix: Use bitwise OR to set, AND with NOT to clear, and XOR to toggle bits
Mistake: Forgetting to shift 1 by the bit position before applying bitwise operation
Fix: Always create mask by shifting 1 left by pos before bitwise operation
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.
The key is to create a mask with 1 shifted to the bit position and use OR, AND, or XOR.

Practice

(1/5)
1. What does the operation num | (1 << pos) do to the bit at position pos in num?
easy
A. Sets the bit at position pos to 1
B. Clears the bit at position pos to 0
C. Toggles the bit at position pos
D. Checks if the bit at position pos is set

Solution

  1. Step 1: Understand the bitwise OR with shifted 1

    The expression 1 << pos creates a number with only the bit at position pos set to 1, all others 0.
  2. Step 2: Apply OR operation to set the bit

    Using num | (1 << pos) sets the bit at pos to 1 regardless of its previous value, leaving other bits unchanged.
  3. Final Answer:

    Sets the bit at position pos to 1 -> Option A
  4. Quick Check:

    OR with 1 at pos sets bit to 1 [OK]
Hint: OR with 1 at position sets that bit to 1 [OK]
Common Mistakes:
  • Confusing OR with XOR for toggling
  • Thinking it clears the bit instead of setting
  • Assuming it checks the bit instead of modifying
2. Which of the following Rust code snippets correctly clears (sets to 0) the bit at position pos in num?
easy
A. num & (1 << pos)
B. num & !(1 << pos)
C. num | !(1 << pos)
D. num ^ (1 << pos)

Solution

  1. Step 1: Create mask with 0 at pos and 1 elsewhere

    The expression !(1 << pos) creates a mask with all bits 1 except bit pos which is 0.
  2. Step 2: AND operation clears bit at pos

    Using num & !(1 << pos) clears the bit at pos to 0, keeping other bits unchanged.
  3. Final Answer:

    num & !(1 << pos) -> Option B
  4. Quick Check:

    AND with inverted mask clears bit [OK]
Hint: AND with NOT mask clears bit at position [OK]
Common Mistakes:
  • Using OR instead of AND to clear bits
  • Forgetting to invert the mask
  • Using XOR which toggles instead of clears
3. What is the output of the following Rust code?
let mut num = 0b1010; // binary 10
let pos = 1;
num ^= 1 << pos;
println!("{:04b}", num);
medium
A. 1000
B. 1010
C. 1011
D. 1110

Solution

  1. Step 1: Understand initial value and bit position

    Initial num is binary 1010 (decimal 10). Position pos is 1 (counting from 0 at right).
  2. Step 2: Toggle bit at position 1 using XOR

    1 << pos is 0010. XOR toggles bit 1: 1010 XOR 0010 = 1000 (decimal 8).
  3. Final Answer:

    1000 -> Option A
  4. Quick Check:

    XOR toggles bit 1: 1010 -> 1000 [OK]
Hint: XOR with 1 toggles the bit at position [OK]
Common Mistakes:
  • Confusing XOR with OR or AND
  • Miscounting bit positions
  • Printing decimal instead of binary
4. Identify the error in this Rust code that tries to toggle the bit at position pos in num:
let mut num = 0b1001;
let pos = 2;
num = num | (1 << pos);
num = num ^ (1 << pos);
println!("{:04b}", num);
medium
A. The code will cause a compile error
B. The bit position is out of range
C. The bit is toggled twice, so no change occurs
D. The OR operator should be AND to toggle

Solution

  1. Step 1: Analyze the first operation (OR)

    num | (1 << pos) sets bit 2 to 1. Bit 2 was 0 in 1001, so num becomes 1101.
  2. Step 2: Analyze the second operation (XOR)

    num ^ (1 << pos) toggles bit 2 from 1 back to 0, resulting in 1001.
  3. Step 3: Check final output

    After both operations, bit 2 was set then toggled back, so no net change occurs.
  4. Final Answer:

    The bit is toggled twice, so no change occurs -> Option C
  5. Quick Check:

    Setting then toggling same bit cancels out [OK]
Hint: Setting then toggling same bit cancels effect [OK]
Common Mistakes:
  • Assuming OR then XOR always toggles bit
  • Ignoring bit position indexing
  • Expecting compile error where none exists
5. Given a 8-bit number num = 0b11001100, write the result after toggling bits at positions 2, 3, and 7 in sequence using Rust bitwise operations. What is the final binary value?
hard
A. 10001100
B. 01001100
C. 11001100
D. 01000000

Solution

  1. Step 1: Initial value and bit positions

    Initial num is 11001100 (bits 7 to 0). Positions to toggle: 2, 3, 7.
  2. Step 2: Toggle bit 2

    Bit 2 is 1 (counting from 0 rightmost). Toggle flips it to 0: 11001100 -> 11001000.
  3. Step 3: Toggle bit 3

    Bit 3 is 1. Toggle flips it to 0: 11001000 -> 11000000.
  4. Step 4: Toggle bit 7

    Bit 7 is 1. Toggle flips it to 0: 11000000 -> 01000000.
  5. Step 5: Final binary value

    Final value is 01000000 in binary (bits 7,3,2 toggled to 0, others unchanged).
  6. Final Answer:

    01000000 -> Option D
  7. Quick Check:

    Toggle bits 2,3,7 flips those bits [OK]
Hint: Toggle bits one by one with XOR [OK]
Common Mistakes:
  • Miscounting bit positions from right
  • Forgetting to toggle bits in sequence
  • Confusing toggle with set or clear
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard