# First and Last Three Bits in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a number N. Our task is to find the decimal conversion of the fist three and last three bits for the given integer values N.

Let's take an example to understand the problem,

Input : 57
Output : 71

## Solution Approach

A simple solution is by changing the number n into its binary equivalent and then saving the bits in an array. After this, we will convert the first three and last three values from the array into numbers individually. The decimal conversion of both the sets of bits is our result.

For example, take the number 80.

The binary conversion of 80 is 1010000.

The decimal conversion of the first three bits (101) is 5.

The decimal equivalent of the last three bits (000) is 0.

Hence the output is 5 0.

## Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
void convtbnTodcml(int n)
{
int arr[64] = { 0 };
int x = 0, index;
for (index = 0; n > 0; index++) {
arr[index] = n % 2;
n /= 2;
}
x = (index < 3) ? 3 : index;
int d = 0, p = 0;
for (int index = x - 3; index < x; index++)
d += arr[index] * pow(2, p++);
cout << d << " ";
d = 0;
p = 0;
for (int index = 0; index < 3; index++)
d += arr[index] * pow(2, p++);
cout << d;
}
int main()
{
int n = 57;
cout<<"Decimal conversion of first and last bits of the number "<<n<<" is ";
convtbnTodcml(n);
return 0;
}

## Output

Decimal conversion of first and last bits of the number 57 is 7 1

Updated on 01-Feb-2022 09:51:49