How to convert binary number to decimal in Python

1 Answer

0 votes
def binary_to_decimal(s): 
    dec = 0
    j = 0
 
    for i in range(len(s) - 1, -1, -1): # range (start, stop[, step])
        if (s[i] == '1'):
            dec += pow(2, j)
        j += 1
    return dec; 
 

s = "10101011";  
   
print(binary_to_decimal(s))



'''
run:

171

'''

 



answered May 9, 2019 by avibootz

Related questions

1 answer 145 views
3 answers 160 views
2 answers 149 views
2 answers 195 views
1 answer 135 views
...