Python - Convert binary to decimal

Introduction

Each time through the loop, multiply the current value by 2 and add the next digit's integer value:

Demo

B = '1101'                 # Convert binary digits to integer with ord 
I = 0 # from   w  w w .  ja va  2 s.com
while B != '': 
    I = I * 2 + (ord(B[0]) - ord('0')) 
    B = B[1:] 
print( I )

Result

A left-shift operation (I << 1) would have the same effect as multiplying by 2 here.

You can use the following function to convert int to binary back and forth.

Demo

print( int('1101', 2) )             # Convert binary to integer: built-in 
print( bin(13) )                    # Convert integer to binary: built-in

Result

Related Topic