First and Last Three Bits | Python 3 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
from math import pow NEW_LINE def binToDecimal3 ( n ) : NEW_LINE INDENT a = [ 0 for i in range ( 64 ) ] NEW_LINE x = 0 NEW_LINE i = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT a [ i ] = n % 2 NEW_LINE n = int ( n / 2 ) NEW_LINE i += 1 NEW_LINE DEDENT if ( i < 3 ) : NEW_LINE INDENT x = 3 NEW_LINE DEDENT else : NEW_LINE INDENT x = i NEW_LINE DEDENT d = 0 NEW_LINE p = 0 NEW_LINE for i in range ( x - 3 , x , 1 ) : NEW_LINE INDENT d += a [ i ] * pow ( 2 , p ) NEW_LINE p += 1 NEW_LINE DEDENT print ( int ( d ) , end = " ▁ " ) NEW_LINE d = 0 NEW_LINE p = 0 NEW_LINE for i in range ( 0 , 3 , 1 ) : NEW_LINE INDENT d += a [ i ] * pow ( 2 , p ) NEW_LINE p += 1 NEW_LINE DEDENT print ( int ( d ) , end = " ▁ " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 86 NEW_LINE binToDecimal3 ( n ) NEW_LINE DEDENT