Using bitwise OR (|) with a mask to set multiple bits in an integer: is this a valid and common technique?

Difficulty: Easy

Correct Answer: Yes — x = x | mask (or x |= mask) sets all bits that are 1 in mask

Explanation:


Introduction / Context:
Bit-setting with OR is one of the first mask techniques developers learn. It is used in flag fields, permissions, device registers, and protocol headers. The expression combines the existing bits with a mask where ones indicate which positions to turn on.


Given Data / Assumptions:

  • x is an integer whose bits we want to modify.
  • mask has 1s in the positions to set and 0s elsewhere.
  • We perform x |= mask (or x = x | mask).


Concept / Approach:
OR has the truth table: 0|0=0, 0|1=1, 1|0=1, 1|1=1. Therefore, any position that is already 1 stays 1, and any position that is 0 becomes 1 when the mask has a 1 in that position. As a result, OR “sets” the specified bits and leaves others unchanged.


Step-by-Step Solution:

Choose mask = (1u << k) | (1u << j) | … for the positions to set.Compute x |= mask.Verify the targeted bits are now 1; other bits remain as before.


Verification / Alternative check:
Example: x = 0b0101, mask = 0b1010 → x | mask = 0b1111; both bits 1 and 3 are now set.


Why Other Options Are Wrong:

“Only AND can set bits”: AND typically clears bits; it cannot turn a 0 into 1.Endianness has no effect on the logical outcome of OR on integer values.“Only for a single bit” or “Requires shifting and addition”: OR with a composed mask sets any number of bits; addition is not needed.


Common Pitfalls:
Confusing OR for setting with AND-for-clearing; not using unsigned when building shift-based masks.


Final Answer:
Yes — x = x | mask (or x |= mask) sets all bits that are 1 in mask.

Discussion & Comments

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