In C, can the bitwise OR operator (|) be used to set a particular bit of an integer value (for example, set bit k using n | (1 << k))?

Difficulty: Easy

Correct Answer: Yes—use n | (1 << k) to set bit k.

Explanation:


Introduction / Context:
This question checks bit manipulation fluency in C: specifically, whether the bitwise OR operator can set a target bit in an integer without affecting other bits.



Given Data / Assumptions:

  • We have an integer n.
  • We want to set bit position k (0-based from the least significant bit).
  • Standard two’s complement system.


Concept / Approach:
The classic pattern to set a bit is: n_new = n | (1 << k). The mask (1 << k) has a 1 only at position k. ORing preserves existing 1s and turns bit k into 1 regardless of its prior state.



Step-by-Step Solution:
Create mask: mask = 1 << k.Apply OR: n_new = n | mask.All bits except k remain as in n; bit k becomes 1.No other bits are cleared or toggled; OR only adds ones where the mask has ones.


Verification / Alternative check:
Test example: n = 0b0101, k = 2 → mask = 0b0100 → n | mask = 0b0101 | 0b0100 = 0b0101 (bit already set). If n = 0b0001, k = 2 → result 0b0101, which shows the set operation.



Why Other Options Are Wrong:
AND is used to clear bits with complements, not to set. XOR toggles a bit and may undesirably clear a previously set bit. Floating-point and pointer arithmetic claims are unrelated.



Common Pitfalls:
Confusing set vs clear vs toggle; off-by-one errors in k; forgetting parentheses around (1 << k) in more complex expressions.



Final Answer:
Yes—use n | (1 << k) to set bit k.

More Questions from Bitwise Operators

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion