Question:

Given an unsigned 32-bit integer \( x \), which of the following C/C++ expressions correctly toggles its bits starting from position \( p \) (with the least significant bit at position 0)? 

Assume: \( x \) is the input integer; \( p \) is the starting position of the bit range (0-based, LSB at position 0); \( m \) is the number of bits to toggle; and no overflow or invalid input conditions occur. Which of the following correctly toggles \( m \) bits starting from position \( p \)?

Show Hint

To toggle specific bits in an integer, use XOR with a mask that has the required bits set to 1 at the correct positions.
Updated On: Oct 7, 2025
  • \( x \, \hat{} \, ((1 \ll m) - 1) \ll p \)
  • \( x | ((1 \ll m) \ll p) \)
  • \( x \, \hat{} \, ((1 \ll m) \ll p) \)
  • x & ∼ ((1≪m)−1)≪p
     

Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is A

Solution and Explanation

To toggle \( m \) bits starting from position \( p \), we need to create a mask that has \( m \) bits set to 1, starting at position \( p \). This is achieved using the following logic: 
1. \( (1 \ll m) \) shifts 1 left by \( m \) positions, creating a number with the first \( m \) bits as 1. 

2. Subtracting 1 from this number (i.e., \( (1 \ll m) - 1 \)) creates a number with the first \( m \) bits set to 1 and the rest set to 0. 

3. Shifting this mask by \( p \) positions, i.e., \( ((1 \ll m) - 1) \ll p \), ensures that the mask starts at position \( p \). 

4. Finally, XORing \( x \) with this mask (using the `^` operator) will toggle the bits at the specified positions. 

Thus, the correct expression is option (a).

Was this answer helpful?
0
0

Questions Asked in NIMCET exam

View More Questions