Find The Toggle Bits Of A Number Except The First And Last Bits In C++

In this article, we will find the toggle bits of a number except the first and last bits in C++.

Given a number, the aim is to toggle everything except the first and final bit.

Examples:

Input: 11

Output: 13

Binary representation:- 1 0 1 1

After toggling first and last: 1 1 0 1

Now, create a collection of numbers that include the middle bit. We must set all center bits to 1 while keeping corner bits alone.

Approach 1: Using XOR

The solution is XOR of the produced and original numbers. It's important to note that combining 1 with a number toggles the number.

Example 1:

Let us take an example to find the toggle bits of a number except the first and last bits using XOR in C++.

Example

#include<iostream>
using namespace std;
// the return value
int setmiddlebitsvalue(int nm)
{
	//setting of all bits
	nm |= nm >> 1;
	nm |= nm >> 2;
	nm |= nm >> 4;
	nm |= nm >> 8;
	nm |= nm >> 16;

	// return the middle set bits 
	// shift by 1 and xor with 1
	return (nm >> 1) ^ 1;
}
int togglemiddle(int nm)
{
	//If the value of the number is 1, then return 
	if (nm == 1)
		return 1;
	// xor value
	return nm ^ setmiddlebitsvalue(nm);
}
// Driver Code
int main()
{
	// the input value
	int nm = 12;
	// displaying the result
	cout<<togglemiddle(nm);

	return 0;
}

Output:

Approach 2: Using a bit mask

In order to fix this problem, we may utilize XOR of a certain bit with 1 to toggle the relevant bit. As a result, we can create a bit mask of the type 0111....11110 for a n - bit integer, i.e., a n-bit number with all bits set except the first and last bit. As a result, the bit masking is equal to 2n - 2 for a number higher than or equal to 4.

Example 2:

Let us take an example to find the toggle bits of a number except the first and last bits using a bit mask in C++.

Example

#include<bits/stdc++.h>
using namespace std;

// function for toggling of bits 
int togglemiddle(int num)
{
	//if the value of num<4
	if (num< 4)
		return num;
	int masks = (1 << (int)log2(num)) - 2;
	return masks ^ num;
}

// Main section
int main()
{
	// the input value
	int number = 8;
	
	//Function calling
	cout << togglemiddle(number) << endl;

	return 0;
}

Output:

Explanation

  • In this example, the function returns the input number when the value is less than four.
  • When the value is higher than or equal to 4, it computes a bit mask based on the highest bit set in the given value and then executes a bitwise XOR operation to toggle the bits depending on that mask.
  • For example, when the number is 8:
  • The binary equivalent of 8 is 1000.
  • (1 (int)log2(8)) - 2 equals 1110.
  • XOR 1000 with 1110 gives 0110 (binary), which is equivalent to 6 in decimal.
  • As a result, togglemiddle(8) returns a value of 6.

Input Required

This code uses input(). Please provide values below: