Bird
Raised Fist0
DSA Goprogramming

Set Clear Toggle a Specific Bit in DSA Go

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 bit. Setting turns a switch on, clearing turns it off, and toggling flips its current state.
Bits:  7 6 5 4 3 2 1 0
Value: 0 0 0 0 1 1 0 1
             ↑
          bit index 2
Dry Run Walkthrough
Input: number = 13 (binary 00001101), bit index = 2
Goal: Set bit 2 to 1, clear bit 2 to 0, and toggle bit 2
Step 1: Set bit 2 to 1 using OR with mask 00000100
00001101 (13) -> 00001101 (13)
Why: Bit 2 is already 1, so setting it keeps the number unchanged
Step 2: Clear bit 2 to 0 using AND with mask 11111011
00001101 (13) -> 00001001 (9)
Why: Clearing bit 2 turns that bit off, changing 13 to 9
Step 3: Toggle bit 2 using XOR with mask 00000100
00001001 (9) -> 00001101 (13)
Why: Toggling flips bit 2 from 0 back to 1, restoring 13
Result:
Final values after operations:
Set bit 2: 13 (00001101)
Clear bit 2: 9 (00001001)
Toggle bit 2: 13 (00001101)
Annotated Code
DSA Go
package main

import (
	"fmt"
)

// setBit sets the bit at pos to 1
func setBit(n int, pos uint) int {
	return n | (1 << pos) // OR with mask to set bit
}

// clearBit clears the bit at pos to 0
func clearBit(n int, pos uint) int {
	return n &^ (1 << pos) // AND NOT with mask to clear bit
}

// toggleBit flips the bit at pos
func toggleBit(n int, pos uint) int {
	return n ^ (1 << pos) // XOR with mask to flip bit
}

func main() {
	n := 13 // binary 00001101
	pos := uint(2)

	set := setBit(n, pos)
	clear := clearBit(n, pos)
	toggle := toggleBit(clear, pos)

	fmt.Printf("Set bit %d: %d (%.8b)\n", pos, set, set)
	fmt.Printf("Clear bit %d: %d (%.8b)\n", pos, clear, clear)
	fmt.Printf("Toggle bit %d: %d (%.8b)\n", pos, toggle, toggle)
}
return n | (1 << pos) // OR with mask to set bit
Set bit at position pos to 1 by ORing with mask
return n &^ (1 << pos) // AND NOT with mask to clear bit
Clear bit at position pos to 0 by AND NOT with mask
return n ^ (1 << pos) // XOR with mask to flip bit
Toggle bit at position pos by XORing with mask
set := setBit(n, pos)
Apply setBit to original number
clear := clearBit(n, pos)
Apply clearBit to original number
toggle := toggleBit(clear, pos)
Toggle bit on cleared number to demonstrate flip
OutputSuccess
Set bit 2: 13 (00001101) Clear bit 2: 9 (00001001) Toggle bit 2: 13 (00001101)
Complexity Analysis
Time: O(1) because bitwise operations take constant time regardless of input size
Space: O(1) because no extra space is needed beyond variables
vs Alternative: Compared to looping through bits or using string conversions, bitwise operations are much faster and use less memory
Edge Cases
bit index out of range (e.g., pos >= number of bits in int)
Operations shift by large amounts but Go handles shifts safely; result may be unchanged or zero
DSA Go
No explicit guard; Go language shift behavior handles this safely
number is zero
Setting bit turns that bit on; clearing keeps zero; toggling flips bit
DSA Go
No special guard needed; bitwise ops work normally
bit already set when setting
Number remains unchanged
DSA Go
No guard needed; OR operation preserves set bits
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 left shift with a negative or out-of-range position causing unexpected results
Fix: Ensure bit position is non-negative and within valid range before shifting
Mistake: Using OR to clear a bit instead of AND NOT
Fix: Use AND NOT (&^) to clear bits, not OR
Mistake: Using XOR to set a bit which may flip it off if already set
Fix: Use OR to set bits to ensure they become 1
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 using bitwise OR to set, AND NOT to clear, and XOR to toggle bits.

Practice

(1/5)
1. What does the operation num |= (1 << 3) do to the number num?
easy
A. Sets the 4th bit of num to 1
B. Clears the 4th bit of num to 0
C. Toggles the 4th bit of num
D. Checks if the 4th bit of num is set

Solution

  1. Step 1: Understand bit shifting

    The expression 1 << 3 shifts 1 left by 3 bits, resulting in binary 00001000, which targets the 4th bit.
  2. Step 2: Apply bitwise OR to set bit

    Using |= with this mask sets the 4th bit of num to 1 without changing other bits.
  3. Final Answer:

    Sets the 4th bit of num to 1 -> Option A
  4. Quick Check:

    Set bit = |= (1 << position) [OK]
Hint: Use OR with shifted 1 to set a bit [OK]
Common Mistakes:
  • Confusing set with clear operation
  • Using wrong bit position (off by one)
  • Thinking it toggles instead of sets
2. Which of the following Go code snippets correctly clears the 2nd bit (bit index 1) of an integer variable num?
easy
A. num &= (1 << 1)
B. num |= (1 << 1)
C. num &= ^(1 << 1)
D. num ^= (1 << 1)

Solution

  1. Step 1: Identify clearing operation

    To clear a bit, we AND num with the inverse mask that has 0 at the target bit and 1 elsewhere.
  2. Step 2: Use bitwise AND with negated mask

    ^(1 << 1) creates a mask with all bits 1 except the 2nd bit 0. ANDing clears that bit.
  3. Final Answer:

    num &= ^(1 << 1) -> Option C
  4. Quick Check:

    Clear bit = &= ^(1 << position) [OK]
Hint: Use AND with negated shifted 1 to clear bit [OK]
Common Mistakes:
  • Using OR instead of AND to clear
  • Not negating the mask
  • Confusing bit index counting
3. What is the output of the following Go code?
package main
import "fmt"
func main() {
    num := 10 // binary 1010
    num ^= (1 << 1)
    fmt.Println(num)
}
medium
A. 10
B. 8
C. 12
D. 14

Solution

  1. Step 1: Understand initial value and bit positions

    Number 10 in binary is 1010. Bit positions (0-based) from right: bit0=0, bit1=1, bit2=0, bit3=1.
  2. Step 2: Toggle 2nd bit (bit index 1) using XOR

    XOR with (1 << 1) toggles bit1. Bit1 is 1, toggling it changes to 0. New binary: 1000 which is 8.
  3. Final Answer:

    8 -> Option B
  4. Quick Check:

    Toggle bit = ^= (1 << position) [OK]
Hint: XOR toggles bit: 1->0 or 0->1 [OK]
Common Mistakes:
  • Confusing toggle with set or clear
  • Misreading bit positions
  • Calculating decimal incorrectly
4. The following Go code is intended to clear the 3rd bit (bit index 2) of num. What is the error?
num := 15
num &= (1 << 2)
medium
A. It sets the 3rd bit instead of clearing it
B. No error, it correctly clears the 3rd bit
C. It toggles the 3rd bit instead of clearing
D. It clears all bits except the 3rd bit

Solution

  1. Step 1: Analyze the operation performed

    The code does num &= (1 << 2), which ANDs num with 00000100 (only 3rd bit set).
  2. Step 2: Understand effect on bits

    This clears all bits except the 3rd bit, effectively keeping only the 3rd bit if it was set, not clearing it.
  3. Final Answer:

    It clears all bits except the 3rd bit -> Option D
  4. Quick Check:

    Clear bit = &= ^(1 << position) [OK]
Hint: Use AND with negated mask to clear bit [OK]
Common Mistakes:
  • Using AND with mask instead of negated mask
  • Confusing clear with set or toggle
  • Assuming &= (1 << n) clears bit
5. You have an integer num initially 0. You want to toggle the 1st bit, set the 3rd bit, and clear the 2nd bit in this order. Which sequence of operations achieves this correctly in Go?
hard
A. num ^= (1 << 0); num |= (1 << 2); num &= ^(1 << 1)
B. num |= (1 << 0); num ^= (1 << 2); num &= ^(1 << 1)
C. num &= ^(1 << 1); num ^= (1 << 0); num |= (1 << 2)
D. num |= (1 << 2); num ^= (1 << 0); num &= ^(1 << 1)

Solution

  1. Step 1: Toggle 1st bit (bit 0)

    Use XOR with (1 << 0) to toggle the 1st bit: num ^= (1 << 0).
  2. Step 2: Set 3rd bit (bit 2)

    Use OR with (1 << 2) to set the 3rd bit: num |= (1 << 2).
  3. Step 3: Clear 2nd bit (bit 1)

    Use AND with negated mask to clear 2nd bit: num &= ^(1 << 1).
  4. Final Answer:

    num ^= (1 << 0); num |= (1 << 2); num &= ^(1 << 1) -> Option A
  5. Quick Check:

    Toggle, Set, Clear in order with ^=, |=, &= ^ [OK]
Hint: Toggle ^=, Set |=, Clear &= ^ in correct order [OK]
Common Mistakes:
  • Mixing order of operations
  • Using wrong operators for each action
  • Not negating mask when clearing
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