In this tutorial, we will explore how to determine the toggle bits within a number excluding the initial and final bits using C++.
The objective is to invert all bits in a number, except for the first and last bits.
Examples:
Input: 11
Output: 13
Binary representation:- 1 0 1 1
After toggling first and last: 1 1 0 1
Now, generate a set of numbers that encompass the central portion. It is necessary to assign a value of 1 to all middle segments while leaving the edge segments unchanged.
Approach 1: Using XOR
The result is the XOR operation between the generated and initial numbers. It's crucial to highlight that pairing 1 with a number flips the number.
Example 1:
Let's consider a scenario where we want to determine the toggled bits of a number excluding the initial and final bits by employing the XOR operation in C++.
#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
To resolve this issue, we can employ XOR operation with a specific bit set to 1 to switch the corresponding bit. Consequently, we can generate a bit pattern like 0111....11110 for an n-bit integer, representing a number with all bits activated except the first and last ones. Therefore, the bit manipulation amounts to 2n - 2 for a value greater than or equal to 4.
Example 2:
Let's consider a scenario where we want to identify the toggle bits within a number, excluding the first and last bits, by employing a bit mask in the C++ programming language.
#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.