First and Last Three Bits | C ++ implementation of the approach ; Function to print the first and last 3 bits equivalent decimal number ; Converting n to binary ; Length of the array has to be at least 3 ; Convert first three bits to decimal ; Print the decimal ; Convert last three bits to decimal ; Print the decimal ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void binToDecimal3 ( int n ) { int a [ 64 ] = { 0 } ; int x = 0 , i ; for ( i = 0 ; n > 0 ; i ++ ) { a [ i ] = n % 2 ; n /= 2 ; } x = ( i < 3 ) ? 3 : i ; int d = 0 , p = 0 ; for ( int i = x - 3 ; i < x ; i ++ ) d += a [ i ] * pow ( 2 , p ++ ) ; cout << d << " ▁ " ; d = 0 ; p = 0 ; for ( int i = 0 ; i < 3 ; i ++ ) d += a [ i ] * pow ( 2 , p ++ ) ; cout << d ; } int main ( ) { int n = 86 ; binToDecimal3 ( n ) ; return 0 ; }