Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Set Clear Toggle a Specific Bit in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Set Clear Toggle a Specific Bit
What is it?
Setting, clearing, and toggling a specific bit means changing one particular bit in a number's binary form. Setting a bit means making it 1, clearing means making it 0, and toggling means switching it from 0 to 1 or from 1 to 0. These operations let us control individual bits inside numbers, which is useful in many programming tasks. They work by using simple math and logic on the binary digits of numbers.
Why it matters
Without the ability to change specific bits, programmers would have to rewrite entire numbers to change small parts, which is slow and error-prone. Bit operations let us efficiently store and manipulate data, control hardware, and optimize performance. For example, turning on or off features in a program or checking flags is much easier with these bit tricks. Without them, many fast and compact programs would be impossible.
Where it fits
Before learning this, you should understand binary numbers and basic logic operations like AND, OR, and XOR. After mastering bit setting, clearing, and toggling, you can learn about bit masks, bit shifts, and how to use bits for flags and permissions in real applications.
Mental Model
Core Idea
Changing a specific bit in a number is like flipping a single light switch in a row of switches without touching the others.
Think of it like...
Imagine a row of light switches controlling different lamps. Setting a bit is like turning a switch ON, clearing is turning it OFF, and toggling is flipping the switch to the opposite position. You only touch one switch at a time, leaving the rest unchanged.
Number bits:  0 0 1 0 1 1 0 1
Index:        7 6 5 4 3 2 1 0

Set bit 4:    0 0 1 1 1 1 0 1  (bit 4 changed from 0 to 1)
Clear bit 2:  0 0 1 0 1 0 0 1  (bit 2 changed from 1 to 0)
Toggle bit 0: 0 0 1 0 1 1 0 0  (bit 0 flipped from 1 to 0)
Build-Up - 7 Steps
1
FoundationUnderstanding Binary Number Basics
🤔
Concept: Learn how numbers are represented in binary and what bits mean.
Every number in a computer is stored as a series of bits (0s and 1s). Each bit represents a power of two, starting from the right (least significant bit). For example, the number 13 in binary is 1101, which means 1*8 + 1*4 + 0*2 + 1*1 = 13. Knowing this helps us understand how to change individual bits.
Result
You can read and write numbers in binary and identify each bit's position.
Understanding binary is essential because bit operations directly manipulate these 0s and 1s, not the decimal number.
2
FoundationBasic Bitwise Operators Explained
🤔
Concept: Introduce AND, OR, XOR, and NOT operators used to manipulate bits.
Bitwise AND (&) compares two bits and returns 1 only if both are 1. OR (|) returns 1 if at least one bit is 1. XOR (^) returns 1 if bits are different. NOT (~) flips all bits. For example, 5 & 3 = 1 because 0101 & 0011 = 0001. These operators let us change bits selectively.
Result
You can perform simple bit operations and predict their results.
Knowing these operators is key because setting, clearing, and toggling bits use them in specific ways.
3
IntermediateHow to Set a Specific Bit
🤔Before reading on: do you think setting a bit uses AND, OR, or XOR? Commit to your answer.
Concept: Setting a bit means making that bit 1 without changing others, done using OR with a mask.
To set bit n, create a mask with 1 at position n (1 << n). Then OR the number with this mask. For example, to set bit 2 of 8 (1000), mask is 1 << 2 = 0100. 1000 | 0100 = 1100 (12). This changes only bit 2 to 1.
Result
The number now has the chosen bit set to 1, others unchanged.
Understanding OR with a mask shows how to turn on a bit safely without affecting others.
4
IntermediateHow to Clear a Specific Bit
🤔Before reading on: do you think clearing a bit uses AND, OR, or XOR? Commit to your answer.
Concept: Clearing a bit means making that bit 0 without changing others, done using AND with an inverted mask.
To clear bit n, create a mask with 1 at position n (1 << n), then invert it (~mask). AND the number with this inverted mask. For example, clear bit 3 of 15 (1111): mask = 1 << 3 = 1000, ~mask = 0111. 1111 & 0111 = 0111 (7). Bit 3 is cleared.
Result
The number now has the chosen bit cleared to 0, others unchanged.
Knowing how to invert a mask and use AND lets you turn off a bit safely.
5
IntermediateHow to Toggle a Specific Bit
🤔Before reading on: do you think toggling a bit uses AND, OR, or XOR? Commit to your answer.
Concept: Toggling a bit means flipping it from 0 to 1 or 1 to 0, done using XOR with a mask.
To toggle bit n, create a mask with 1 at position n (1 << n). XOR the number with this mask. For example, toggle bit 1 of 5 (0101): mask = 0010. 0101 ^ 0010 = 0111 (7). Bit 1 flipped from 0 to 1.
Result
The number now has the chosen bit flipped, others unchanged.
XOR with a mask is a simple way to flip bits without affecting others.
6
AdvancedImplementing Bit Operations in TypeScript
🤔Before reading on: do you think these operations can be done in one line each? Commit to your answer.
Concept: Show how to write functions in TypeScript to set, clear, and toggle bits using bitwise operators.
function setBit(num: number, bit: number): number { return num | (1 << bit); } function clearBit(num: number, bit: number): number { return num & ~(1 << bit); } function toggleBit(num: number, bit: number): number { return num ^ (1 << bit); } // Example usage: // setBit(8, 2) returns 12 // clearBit(15, 3) returns 7 // toggleBit(5, 1) returns 7
Result
You can call these functions to change bits in numbers easily and correctly.
Knowing how to write reusable functions makes bit manipulation practical and less error-prone.
7
ExpertCommon Pitfalls and Performance Considerations
🤔Before reading on: do you think bit operations are always faster than arithmetic? Commit to your answer.
Concept: Discuss edge cases like negative numbers, operator precedence, and when bit operations might not be faster or safe.
Bitwise operators work on 32-bit signed integers in JavaScript/TypeScript, so negative numbers use two's complement. For example, shifting bits on negative numbers can produce unexpected results. Also, operator precedence matters: use parentheses to avoid bugs. While bit operations are usually fast, modern CPUs optimize arithmetic well, so micro-optimizations may not help. Always test correctness first.
Result
You avoid bugs related to sign bits and operator mistakes, and write safer, clearer code.
Understanding language specifics and hardware helps prevent subtle bugs and misguided optimizations.
Under the Hood
Bitwise operations work by directly manipulating the binary digits stored in the computer's memory. Each number is stored as a fixed-size sequence of bits (usually 32 bits in JavaScript/TypeScript). Operators like AND, OR, XOR, and NOT perform logical operations on each bit pair or single bit, producing a new binary number. Shifting bits moves them left or right, changing their value by powers of two. These operations happen at the processor level using fast machine instructions.
Why designed this way?
Bitwise operators were designed to allow low-level control of data, enabling efficient manipulation of flags, masks, and hardware registers. Early computers had limited memory and processing power, so changing individual bits without affecting others was crucial. The choice of operators reflects fundamental logic gates in digital circuits, making them natural and fast. Alternatives like arithmetic operations are slower or less precise for bit-level control.
Number (32 bits):  [b31 b30 ... b3 b2 b1 b0]

Set bit n:
  mask = 1 << n
  result = number | mask

Clear bit n:
  mask = 1 << n
  inverted_mask = ~mask
  result = number & inverted_mask

Toggle bit n:
  mask = 1 << n
  result = number ^ mask
Myth Busters - 4 Common Misconceptions
Quick: Does toggling a bit always set it to 1? Commit yes or no.
Common Belief:Toggling a bit always sets it to 1.
Tap to reveal reality
Reality:Toggling flips the bit: if it was 0, it becomes 1; if it was 1, it becomes 0.
Why it matters:Assuming toggling always sets bits leads to bugs where bits unexpectedly turn off, causing incorrect program behavior.
Quick: Can you clear a bit using OR? Commit yes or no.
Common Belief:You can clear a bit by using the OR operator with a mask.
Tap to reveal reality
Reality:OR can only set bits to 1, not clear them. Clearing requires AND with an inverted mask.
Why it matters:Using OR to clear bits fails silently, leaving bits set when you want them cleared.
Quick: Are bitwise operations always faster than arithmetic? Commit yes or no.
Common Belief:Bitwise operations are always faster than arithmetic operations.
Tap to reveal reality
Reality:Modern processors optimize arithmetic well; bitwise operations are fast but not always noticeably faster in high-level languages.
Why it matters:Overusing bitwise operations for speed can reduce code clarity without real performance gains.
Quick: Does shifting bits on negative numbers behave the same as positive? Commit yes or no.
Common Belief:Bit shifts behave the same on negative and positive numbers.
Tap to reveal reality
Reality:Negative numbers use two's complement; shifting can produce unexpected results due to sign extension.
Why it matters:Ignoring sign behavior causes bugs in algorithms that manipulate bits of signed integers.
Expert Zone
1
Bitwise operations in JavaScript/TypeScript work on 32-bit signed integers, so numbers outside this range are converted, which can cause unexpected results.
2
Operator precedence can cause subtle bugs; for example, bitwise AND has lower precedence than equality checks, so parentheses are often necessary.
3
Using bitwise operations for flags is memory-efficient but can reduce code readability if not well documented or abstracted.
When NOT to use
Avoid bitwise operations when working with floating-point numbers or very large integers beyond 32 bits, as these operations convert numbers to 32-bit signed integers. Use BigInt or specialized libraries for large numbers. Also, avoid bitwise tricks for clarity-critical code where readability matters more than micro-optimizations.
Production Patterns
In real-world systems, bit operations are used for permission flags, feature toggles, hardware control registers, compression algorithms, and network protocols. Professionals wrap bit operations in clear functions or classes to maintain readability and prevent errors. They also use constants for bit positions and masks to avoid magic numbers.
Connections
Permission Flags in Operating Systems
Bit manipulation is used to represent and check multiple permissions efficiently using bits as flags.
Understanding bit operations helps grasp how OSes store and check read/write/execute permissions compactly.
Digital Logic Circuits
Bitwise operators correspond directly to logic gates like AND, OR, XOR, and NOT used in hardware design.
Knowing bit operations deepens understanding of how computers physically process data at the circuit level.
Genetic Algorithms in Biology
Bit toggling mimics mutation in genetic algorithms where bits represent genes that flip to create variation.
Recognizing bit toggling as mutation connects computer algorithms to natural evolutionary processes.
Common Pitfalls
#1Trying to clear a bit using OR operator.
Wrong approach:let num = 15; // 1111 let bit = 2; num = num | (1 << bit); // Incorrect: this sets bit 2 instead of clearing
Correct approach:let num = 15; // 1111 let bit = 2; num = num & ~(1 << bit); // Correct: clears bit 2
Root cause:Misunderstanding that OR can only set bits to 1, not clear them.
#2Not using parentheses causing wrong operator precedence.
Wrong approach:let num = 5; let bit = 1; let result = num & ~1 << bit; // Wrong: ~ applies to 1 before shift due to precedence
Correct approach:let num = 5; let bit = 1; let result = num & ~(1 << bit); // Correct: shift before NOT, then AND
Root cause:Ignoring operator precedence rules in expressions.
#3Using bitwise operations on numbers larger than 32 bits without care.
Wrong approach:let bigNum = 4294967296; // 2^32 let bit = 0; bigNum = bigNum | (1 << bit); // Unexpected result due to 32-bit conversion
Correct approach:Use BigInt for large numbers: let bigNum = 4294967296n; let bit = 0n; bigNum = bigNum | (1n << bit);
Root cause:Not knowing bitwise operators convert numbers to 32-bit signed integers.
Key Takeaways
Setting, clearing, and toggling bits lets you change individual bits in a number without affecting others.
Use OR with a mask to set bits, AND with an inverted mask to clear bits, and XOR with a mask to toggle bits.
Bitwise operations work on 32-bit signed integers in TypeScript, so be careful with negative numbers and large values.
Operator precedence matters: always use parentheses when combining bitwise operators with others.
Bit manipulation is a powerful tool for efficient data control, but clarity and correctness must come first.

Practice

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

Solution

  1. Step 1: Understand bitwise OR with shifted 1

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

    Using num | (1 << pos) sets the bit at pos to 1 without changing other bits.
  3. Final Answer:

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

    Bitwise OR with 1 at pos sets bit [OK]
Hint: Use OR with shifted 1 to set a bit [OK]
Common Mistakes:
  • Confusing set with clear operation
  • Using AND instead of OR to set bit
  • Thinking it toggles the bit
2. Which of the following TypeScript code snippets correctly clears (sets to 0) the bit at position pos in the variable num?
easy
A. num = num & (1 << pos);
B. num = num & ~(1 << pos);
C. num = num | (1 << pos);
D. num = num ^ (1 << pos);

Solution

  1. Step 1: Understand clearing a bit

    To clear a bit, we AND the number with a mask that has 0 at the target bit and 1s elsewhere.
  2. Step 2: Create mask with NOT operator

    ~(1 << pos) creates a mask with 0 at pos and 1s elsewhere, so num & ~(1 << pos) clears the bit.
  3. Final Answer:

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

    AND with NOT mask clears bit [OK]
Hint: Use AND with NOT shifted 1 to clear bit [OK]
Common Mistakes:
  • Using OR instead of AND to clear bit
  • Forgetting to negate the mask
  • Using XOR which toggles instead of clears
3. What is the output of the following TypeScript code?
let num = 10; // binary 1010
let pos = 1;
num = num ^ (1 << pos);
console.log(num);
medium
A. 8
B. 10
C. 12
D. 14

Solution

  1. Step 1: Understand initial values and bit positions

    Number 10 in binary is 1010. Bit positions (0-based) from right: pos 0=0, pos 1=1, pos 2=0, pos 3=1.
  2. Step 2: Apply XOR to toggle bit at position 1

    1 << 1 is 2 (binary 0010). XOR toggles bit 1: 1010 ^ 0010 = 1000 (binary), which is 8 decimal.
  3. Final Answer:

    8 -> Option A
  4. Quick Check:

    Toggle bit 1 in 10 gives 8 [OK]
Hint: XOR toggles bit; toggle 1 in 1010 gives 1000 (8) [OK]
Common Mistakes:
  • Confusing XOR with OR or AND
  • Miscounting bit positions
  • Assuming toggle sets bit always to 1
4. The following TypeScript code is intended to toggle the bit at position pos in num. What is the error?
let num = 5; // binary 0101
let pos = 2;
num = num & (1 << pos);
console.log(num);
medium
A. It only keeps the bit at pos and clears others
B. It clears the bit instead of toggling
C. It sets the bit instead of toggling
D. It causes a syntax error

Solution

  1. Step 1: Analyze the operation used

    The code uses num & (1 << pos), which ANDs num with a mask having 1 only at pos.
  2. Step 2: Understand effect of AND with mask

    This operation keeps only the bit at pos and clears all other bits, not toggling the bit.
  3. Final Answer:

    It only keeps the bit at pos and clears others -> Option A
  4. Quick Check:

    AND with mask keeps only that bit [OK]
Hint: AND with mask keeps only that bit, doesn't toggle [OK]
Common Mistakes:
  • Confusing AND with XOR for toggling
  • Expecting toggle but using AND
  • Ignoring effect on other bits
5. You have a number num = 29 (binary 11101). You want to toggle the bits at positions 0, 2, and 4 simultaneously. Which TypeScript code correctly does this?
hard
A. num = num | ((1 << 0) & (1 << 2) & (1 << 4));
B. num = num & ~((1 << 0) | (1 << 2) | (1 << 4));
C. num = num ^ ((1 << 0) | (1 << 2) | (1 << 4));
D. num = num ^ (1 << 0) & (1 << 2) & (1 << 4);

Solution

  1. Step 1: Create mask for bits 0, 2, and 4

    Using OR to combine shifted bits: (1 << 0) | (1 << 2) | (1 << 4) creates mask 10101 binary (decimal 21).
  2. Step 2: Use XOR to toggle bits

    XOR with this mask toggles bits 0, 2, and 4 in num.
  3. Final Answer:

    num = num ^ ((1 << 0) | (1 << 2) | (1 << 4)); -> Option C
  4. Quick Check:

    XOR with combined mask toggles multiple bits [OK]
Hint: Combine bits with OR, toggle with XOR [OK]
Common Mistakes:
  • Using AND or OR instead of XOR to toggle
  • Using AND between shifted bits instead of OR
  • Not combining bits before toggling
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