Convert from any base to decimal and vice versa | To return value of a char . For example , 2 is returned for '2' . 10 is returned for ' A ' , 11 for 'B ; Function to convert a number from given base ' b ' to decimal ; Initialize power of base ; Initialize result ; Decimal equivalent is str [ len - 1 ] * 1 + str [ len - 2 ] * base + str [ len - 3 ] * ( base ^ 2 ) + ... ; A digit in input number must be less than number 's base ; Driver code
' NEW_LINE def val ( c ) : NEW_LINE INDENT if c >= '0' and c <= '9' : NEW_LINE INDENT return ord ( c ) - ord ( '0' ) NEW_LINE DEDENT else : NEW_LINE INDENT return ord ( c ) - ord ( ' A ' ) + 10 ; NEW_LINE DEDENT DEDENT def toDeci ( str , base ) : NEW_LINE INDENT llen = len ( str ) NEW_LINE DEDENT power = 1 NEW_LINE num = 0 NEW_LINE INDENT for i in range ( llen - 1 , - 1 , - 1 ) : NEW_LINE INDENT if val ( str [ i ] ) >= base : NEW_LINE INDENT print ( ' Invalid ▁ Number ' ) NEW_LINE return - 1 NEW_LINE DEDENT num += val ( str [ i ] ) * power NEW_LINE power = power * base NEW_LINE DEDENT return num NEW_LINE DEDENT strr = "11A " NEW_LINE base = 16 NEW_LINE print ( ' Decimal ▁ equivalent ▁ of ' , strr , ' in ▁ base ' , base , ' is ' , toDeci ( strr , base ) ) NEW_LINE