Bird
Raised Fist0
DSA C#programming

Set Clear Toggle a Specific Bit in DSA C#

Choose your learning style10 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 bulb. 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 1 0 0 1 0
Positions: 7 6 5 4 3 2 1 0
                 ↑
               bit 4
Dry Run Walkthrough
Input: number = 18 (binary 00010010), bit position = 4
Goal: Set, clear, and toggle the bit at position 4 in the number 18
Step 1: Set bit 4 to 1
00010010 (18) -> set bit 4 -> 00010010 (18)
Why: Bit 4 is already 1, so setting it keeps the number unchanged
Step 2: Clear bit 4 to 0
00010010 (18) -> clear bit 4 -> 00000010 (2)
Why: Clearing bit 4 turns off that bit, changing number from 18 to 2
Step 3: Toggle bit 4
00000010 (2) -> toggle bit 4 -> 00010010 (18)
Why: Toggling flips bit 4 from 0 to 1, restoring original number
Result:
Final states:
Set bit 4: 00010010 (18)
Clear bit 4: 00000010 (2)
Toggle bit 4: 00010010 (18)
Annotated Code
DSA C#
using System;

class BitManipulation
{
    // Set bit at position 'pos' to 1
    public static int SetBit(int number, int pos)
    {
        return number | (1 << pos); // Use OR to set bit
    }

    // Clear bit at position 'pos' to 0
    public static int ClearBit(int number, int pos)
    {
        return number & ~(1 << pos); // Use AND with NOT mask to clear bit
    }

    // Toggle bit at position 'pos'
    public static int ToggleBit(int number, int pos)
    {
        return number ^ (1 << pos); // Use XOR to flip bit
    }

    static void Main()
    {
        int number = 18; // binary 00010010
        int pos = 4;

        int setResult = SetBit(number, pos);
        Console.WriteLine($"Set bit {pos}: {Convert.ToString(setResult, 2).PadLeft(8, '0')} ({setResult})");

        int clearResult = ClearBit(number, pos);
        Console.WriteLine($"Clear bit {pos}: {Convert.ToString(clearResult, 2).PadLeft(8, '0')} ({clearResult})");

        int toggleResult = ToggleBit(clearResult, pos);
        Console.WriteLine($"Toggle bit {pos}: {Convert.ToString(toggleResult, 2).PadLeft(8, '0')} ({toggleResult})");
    }
}
return number | (1 << pos);
Set bit by ORing number with mask having 1 at position pos
return number & ~(1 << pos);
Clear bit by ANDing number with inverted mask having 0 at position pos
return number ^ (1 << pos);
Toggle bit by XORing number with mask having 1 at position pos
int setResult = SetBit(number, pos);
Apply set bit operation
int clearResult = ClearBit(number, pos);
Apply clear bit operation
int toggleResult = ToggleBit(clearResult, pos);
Apply toggle bit operation on cleared number
OutputSuccess
Set bit 4: 00010010 (18) Clear bit 4: 00000010 (2) Toggle bit 4: 00010010 (18)
Complexity Analysis
Time: O(1) because bitwise operations take constant time regardless of input size
Space: O(1) because no extra space is used except a few variables
vs Alternative: Using arithmetic or loops to manipulate bits is slower and more complex compared to direct bitwise operations
Edge Cases
bit position outside valid range (e.g., negative or >= number of bits)
Shift operation may cause undefined behavior or no effect; code assumes valid bit positions
DSA C#
No explicit guard; user must provide valid bit positions
number is zero
Setting bit turns on that bit; clearing bit keeps zero; toggling flips bit accordingly
DSA C#
No special guard needed; bitwise ops handle zero correctly
bit already set when setting
Number remains unchanged
DSA C#
return number | (1 << pos);
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 with bitwise operators for efficient manipulation.
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: Not shifting 1 by the correct bit position
Fix: Always shift 1 left by the exact bit position to create the mask
Summary
It changes a 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 by shifting 1 to the bit position and use bitwise OR, AND, or XOR.

Practice

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

Solution

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

    The expression 1 << position creates a number with only the bit at position set to 1. Using OR (|=) with this sets that bit in number to 1 without changing other bits.
  2. Step 2: Effect on the bit at position

    Since OR with 1 always results in 1, the bit at position is set to 1 regardless of its previous value.
  3. Final Answer:

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

    OR with 1 sets bit [OK]
Hint: Use OR with shifted 1 to set a bit [OK]
Common Mistakes:
  • Confusing OR with XOR for toggling
  • Thinking it clears the bit
  • Assuming it checks the bit instead
2. Which of the following C# statements correctly clears (sets to 0) the bit at position pos in an integer num?
easy
A. num &= ~(1 << pos);
B. num |= (1 << pos);
C. num ^= (1 << pos);
D. num = num << pos;

Solution

  1. Step 1: Understand clearing a bit

    To clear a bit, we use AND with the complement of a mask that has 1 at the target bit. The mask is 1 << pos, so complement is ~(1 << pos).
  2. Step 2: Apply AND with complemented mask

    Using num &= ~(1 << pos); clears the bit at pos while leaving others unchanged.
  3. Final Answer:

    num &= ~(1 << pos); -> Option A
  4. Quick Check:

    AND with complement clears bit [OK]
Hint: Use AND with NOT mask to clear a bit [OK]
Common Mistakes:
  • Using OR instead of AND to clear
  • Using XOR which toggles instead of clears
  • Using left shift alone which changes number
3. What is the output of the following C# code?
int num = 10; // binary 1010
int pos = 1;
num ^= (1 << pos);
Console.WriteLine(num);
medium
A. 10
B. 14
C. 12
D. 8

Solution

  1. Step 1: Understand initial number and bit position

    Number 10 in binary is 1010. Position 1 means the second bit from right (0-based). Bit at position 1 is 1.
  2. Step 2: Apply XOR to toggle bit at position 1

    XOR toggles the bit. Since bit at position 1 is 1, toggling it changes it to 0. New binary is 1000 which is decimal 8.
  3. Final Answer:

    8 -> Option D
  4. Quick Check:

    Toggle bit 1 in 1010 = 1000 = 8 [OK]
Hint: XOR toggles bit; 1 becomes 0, 0 becomes 1 [OK]
Common Mistakes:
  • Confusing XOR with OR or AND
  • Miscounting bit positions (0-based)
  • Assuming no change if bit is 1
4. The following code is intended to toggle the bit at position pos in num. What is the error?
int num = 5; // binary 0101
int pos = 2;
num = num & (1 << pos);
Console.WriteLine(num);
medium
A. It clears all bits except the one at pos
B. It toggles the bit correctly
C. It sets the bit at pos to 1
D. It causes a syntax error

Solution

  1. Step 1: Analyze the operation used

    The code uses AND (&) with 1 << pos. This keeps only the bit at pos if it was set, clearing all others.
  2. Step 2: Compare with toggle operation

    Toggling requires XOR (^), not AND. So this code does not toggle but masks all bits except the one at pos.
  3. Final Answer:

    It clears all bits except the one at pos -> Option A
  4. Quick Check:

    AND with mask keeps only that bit [OK]
Hint: Use XOR to toggle, AND masks bits [OK]
Common Mistakes:
  • Using AND instead of XOR for toggle
  • Expecting toggle but getting masked value
  • Confusing bitwise operators
5. You have an integer num and want to toggle the bit at position pos only if it is currently set (1). Which code snippet correctly does this?
hard
A. if ((num ^ (1 << pos)) != 0) num ^= (1 << pos);
B. if ((num & (1 << pos)) != 0) num ^= (1 << pos);
C. if ((num & ~(1 << pos)) != 0) num ^= (1 << pos);
D. if ((num | (1 << pos)) != 0) num ^= (1 << pos);

Solution

  1. Step 1: Check if bit at pos is set

    Using num & (1 << pos) checks if bit at pos is 1. If result is not zero, bit is set.
  2. Step 2: Toggle bit only if set

    If bit is set, toggle it using XOR: num ^= (1 << pos);. This flips the bit from 1 to 0.
  3. Final Answer:

    if ((num & (1 << pos)) != 0) num ^= (1 << pos); -> Option B
  4. Quick Check:

    Check bit with AND, toggle with XOR [OK]
Hint: Check bit with AND before toggling with XOR [OK]
Common Mistakes:
  • Using OR instead of AND to check bit
  • Toggling without checking bit first
  • Using incorrect mask complement
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