2020年4月3日 星期五


                                 

Convert binary to decimal  with Python 


Well! how to convert binary to decimal

For binary number with n digits:
dn-1 ... d3 d2 d1 d0
The decimal number is equal to the sum of binary digits (dn) times their power of 2 (2n):
decimal = d0×20 + d1×21 + d2×22 + ...
There list the sample code of python 
def binaryToDecimal(binary): 
   i = 0
   dec=0
   length=len(binary)
   #print("length")
   #print(length)
   while i< length: 
       if binary[i]=='1':
         dec=dec+2**(length-i)
         #print("dec")
         #print(dec)
       else:
         dec=dec
        # dec = binary % 10
       # decimal = decimal + dec * pow(2, i) 
       # binary = binary//10
       i += 1
   
   return dec    
input binary code :['0', '1', '0', '0', '1', '1', '1', '1', '0', '1', '0', '0', '0', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '0', '1', '1', '1', '0', '1', '0', '1', '1']
output decimal code:  1,330,114,283‬



沒有留言:

張貼留言

if you have any question, please don't hesitate to ask me. Thank you!