Toggle bits of a number except first and last bits

In this blog post, I will teach you how to write a C/C++ program to toggle bits of a number except the first and last bits. After reading this detailed guide post I believe you can write an efficient program to toggle bits of a number except first and last bits.

Consider the examples below for a better understanding to toggle middle bits.

Example-1:

Input : n = 5

Here's a simple ASCII representation of 5 (an 8-bit integer):

  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |  (Example bit values)
+---+---+---+---+---+---+---+---+
  ^                           ^
  |                           |
  Don't toggle these two bits.


 
(After toggling bit all bits except first and last bit) 

Output: 123

  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 1 | 1 | 1 | 1 | 0 | 1 | 1 |  (Example bit values)
+---+---+---+---+---+---+---+---+

 

 

Input : n = 9

Here's a simple ASCII representation of 9 (an 8-bit integer):

  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |  (Example bit values)
+---+---+---+---+---+---+---+---+
  ^                           ^
  |                           |
  Don't toggle these two bits.

 
(After toggling bit all bits except first and last bit) 

Output: 123

  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 1 | 1 | 1 | 0 | 1 | 1 | 1 |  (Example bit values)
+---+---+---+---+---+---+---+---+

 

Let’s see the problem statements for this question.

Problem Statement:Given a positive integer number n, the task is to toggle bits of the number except the first and the last bit.

Disclaimer: Try to solve the problem yourself first otherwise it would be not worth solving this problem.

 

C program to toggle bits of a number except first and last bits:

To write this program you must have understanding of bitwise operators these are the following.

  • Bitwise OR (|): This operator is used to set specific bits to 1.
  • Bitwise XOR (^): This operator is used to toggle bits (flip them between 0 and 1).
  • Bit shifting (>>): This operator moves the bits of a number left or right, allowing us to isolate or modify specific bits.

 

Approach

To solve this problem, we’ll use two main functions:

  1. setMiddleBits: This function will set the middle bits of a number to 1, excluding the first and last bits.
  2. toggleMiddleBits: This function will use setMiddleBits to toggle the middle bits (flip them) of a given number.

The following C code implements the solution to toggle the middle bits of a number while leaving the first and last bits unchanged.

#include <stdio.h>

/**
 * @brief Sets the middle bits (except the first and last bits) of the number.
 *
 * This function progressively shifts the bits of the number to the right and
 * uses bitwise OR to set the bits in the middle. The first and last bits
 * remain unchanged. Afterward, it shifts the result right by 1 and XORs with 1
 * to toggle the middle bits.
 *
 * @param number The number whose middle bits are to be set.
 * @return The number with its middle bits set, excluding the first and last bits.
 */
int setMiddleBits(int number)
{
    // Shift the bits progressively to the right and OR to set bits in the middle
    number |= number >> 1;
    number |= number >> 2;
    number |= number >> 4;
    number |= number >> 8;
    number |= number >> 16;  // Ensure all bit shifts for a 32-bit integer

    // Return the middle set bits (ignoring the first and last bits)
    // By shifting right by 1 and XORing with 1 to toggle the middle bits
    return (number >> 1) ^ 1;
}

/**
 * @brief Toggles the middle bits (except the first and last bits) of the number.
 *
 * This function first checks if the number has fewer than 3 bits. If so, the
 * function returns the number unchanged since there are no middle bits to toggle.
 * Otherwise, it uses XOR with the result from the setMiddleBits function to toggle
 * the middle bits.
 *
 * @param number The number whose middle bits are to be toggled.
 * @return The number with its middle bits toggled, excluding the first and last bits.
 */
int toggleMiddleBits(int number)
{
    // If the number has fewer than 3 bits (1 or 2), no middle bits to toggle
    if (number < 4)
    {
        return number;  // Return the number unchanged
    }

    // Toggle the middle bits using XOR with the middle mask created by setMiddleBits
    return number ^ setMiddleBits(number);
}

/**
 * @brief Main function to test the toggleMiddleBits function.
 *
 * This function serves as a simple driver to demonstrate the toggleMiddleBits
 * function. It prints the original number and the result after toggling the
 * middle bits (except the first and last bits).
 *
 * @return 0 on successful execution.
 */
int main()
{
    // Example number (binary: 1001, decimal: 9)
    int inputNumber = 9;

    // Display the original number and the result after toggling the middle bits
    printf("Original number: %d\n", inputNumber);
    printf("Toggled number: %d\n", toggleMiddleBits(inputNumber));

    return 0;
}

Output:

Original number: 9 (1001)
Toggled number: 15 (1111)

 

 

C++ program to toggle bits of a number except first and last bits:

Using the same concept, you can write the C++ code to toggle bits except the first and last bits.

 

#include <iostream>
using namespace std;

/**
 * @brief Sets the middle bits (except the first and last bits) of the number.
 *
 * This function progressively shifts the bits of the number to the right and
 * uses bitwise OR to set the bits in the middle. The first and last bits
 * remain unchanged. Afterward, it shifts the result right by 1 and XORs with 1
 * to toggle the middle bits.
 *
 * @param number The number whose middle bits are to be set.
 * @return The number with its middle bits set, excluding the first and last bits.
 */
int setMiddleBits(int number)
{
    // Shift the bits progressively to the right and OR to set bits in the middle
    number |= number >> 1;
    number |= number >> 2;
    number |= number >> 4;
    number |= number >> 8;
    number |= number >> 16;  // Ensure all bit shifts for a 32-bit integer

    // Return the middle set bits (ignoring the first and last bits)
    // By shifting right by 1 and XORing with 1 to toggle the middle bits
    return (number >> 1) ^ 1;
}

/**
 * @brief Toggles the middle bits (except the first and last bits) of the number.
 *
 * This function first checks if the number has fewer than 3 bits. If so, the
 * function returns the number unchanged since there are no middle bits to toggle.
 * Otherwise, it uses XOR with the result from the setMiddleBits function to toggle
 * the middle bits.
 *
 * @param number The number whose middle bits are to be toggled.
 * @return The number with its middle bits toggled, excluding the first and last bits.
 */
int toggleMiddleBits(int number)
{
    // If the number has fewer than 3 bits (1 or 2), no middle bits to toggle
    if (number < 4)
    {
        return number;  // Return the number unchanged
    }

    // Toggle the middle bits using XOR with the middle mask created by setMiddleBits
    return number ^ setMiddleBits(number);
}

/**
 * @brief Main function to test the toggleMiddleBits function.
 *
 * This function serves as a simple driver to demonstrate the toggleMiddleBits
 * function. It prints the original number and the result after toggling the
 * middle bits (except the first and last bits).
 *
 * @return 0 on successful execution.
 */
int main()
{
    // Example number (binary: 1001, decimal: 9)
    int inputNumber = 9;

    // Display the original number and the result after toggling the middle bits
    cout << "Original number: " << inputNumber << endl;
    cout << "Toggled number: " << toggleMiddleBits(inputNumber) << endl;

    return 0;
}

 

 

Recommended Post