This post contains a total of 29+ Hand-Picked Python Binary to Decimal Converters with Source Codes. All the Binary to Decimal Converter examples are made using Python Programming language.
You can use the source codes of these programs for your own personal or educational use with credits to the original owner.
Related Posts
Click a Code to Copy it.
1. By David Valladares
Made by David Valladares. Enter a binary number as input and this code will convert it into the equivalent decimal number, You can remove # for showing the hidden lines with intermediate list operations. ( Source )
# Based on the decimal to binary code created by Mitali
number=str(input())
if any([int(i) > 1 for i in number]):
print("That's not a binary number","\n")
else:
print("binary number:\n", number,"\n")
#
#
list_num= [i for [i] in number]
# print(list_num)
list_reverse = list_num[::-1]
# print(list_reverse)
#
#
def powers(x):
count=0
for j in x:
yield int(j)*(2**(len(x)-(count+1)))
count+=1
#
#
list_powers= list(powers(list_num))
decimal_number=sum(list_powers)
# print(list_powers)
print("decimal number:\n", decimal_number,"\n")
#
#
print("Thank you for trying this code!")
print("Hit like if you enjoyed it")
2. By Minase Fikadu
Made by Minase Fikadu. ( Source )
def binaryToDecimal(binary):
'''This function calculates the decimal equivalent to given binary number'''
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
print('Decimal equivalent of {} is {}'.format(binary1, decimal))
if __name__ == '__main__':
userInput = int(input('Enter the binary number to check its decimal equivalent: '))
binaryToDecimal(userInput)
3. By Justine Ogaraku
Made by Justine Ogaraku. ( Source )
def binaryToDecimal(based):
sum = 0;n = 0;based = str(based);length = len(based)
for integer in range(length):
n -= 1;sum += 2**integer * int(based[n])
return sum
print(binaryToDecimal(int(input())))
4. By Zen
Made by Zen. A simple Python program to convert Binary to Decimal. ( Source )
def binToDec(n):
res = 0
i = 1
while n != 0:
res += n%10*i
i *= 2
n = n//10
return res
n = int(input("Binary number?"))
print(str(binToDec(n)))
5. By MEHMET CAN GEZER
Made by MEHMET CAN GEZER. ( Source )
def bintodec(num):
x = str(num)
z = []
for y in range(len(x)):
z.append(x[y])
z = z[::-1]
result = 0
for y in range(len(x)):
result += int(z[y])*(2**y)
return result
num = int(input("Enter a binary value"))
decnum = bintodec(num)
print("Binary",num,"equal","Decimal",decnum)
6. By Shuaib Nuruddin
Made by Shuaib Nuruddin. ( Source )
binary = input()
decimal = 0
for digit in binary:
if int(digit) > 1:
print("Binary only has 0's and 1's,therefore this is not a binary number.Please enter a binary number in the input.")
raise ValueError
decimal = decimal*2 + int(digit)
print(binary,"in binary is",decimal,"in decimal.")
7. By 0xDeed
Made by 0xDeed. ( Source )
import os
import sys
class decimal_to_binary():
def converter_decimal_to_binary(self,decimal):
decimal_binary=decimal
print ("\n#################################")
print("DECIMAL TO BINARY: ",end="")
return bin(decimal_binary)[2::]
class binary_to_decimal():
def converter_binary_to_decimal(self,binary):
binary_to_decimal = binary
decimal = 0
for digit in binary:
if digit == "0" or digit == "1":
decimal = decimal*2 + int(digit)
else:
print("#################################")
return "INVALID"
break
print ("\n#################################")
print ("BINARY TO DECIMAL: ",end="")
return decimal
class text_to_binary():
def text_binary(self,text):
mEncrytp = ''
for letra in text :
final = self.d_binary(ord(letra))
mEncrytp = mEncrytp + str(final) + " "
print("\n#################################")
print("Text to BINARY: ",end="")
return mEncrytp
def d_binary(self,digit):
result = ''
var = digit
temp = 0
i = 0
while i < 8 :
temp = var % 2
result = result + str(temp)
if var==digit :
var = digit//2
else :
var = var//2 #
i = i + 1
return result[::-1]
class binary_to_text() :
def binary_text(self,binary):
list_b = binary.split()
result = ''
for i in range (len(list_b)) :
result = result + chr(self.binary_d(int(list_b[i])))
print("\n#################################")
print("BINARY to Text: ",end="")
return result
def binary_d(self,binary):
digit = 0
i = 0
for iterator in (str(binary)[::-1]) :
if(int(iterator) == 1):
digit = digit + 2 ** i
i = i + 1
return digit
d_b = decimal_to_binary()
b_d = binary_to_decimal()
t_b = text_to_binary()
b_t = binary_to_text()
#start Input
def menu():
#start menu function
print("##########")
print("---Menu---\n")
print("1) Decimal Number to Binary")
print("2) Binary to Decimal Number")
print("3) Text to Binary")
print("4) Binary to Text")
print("5)-Clear-")
print("6)-Exit-\n")
print("---Menu---")
print("##########")
try:
opc =int(input("\nchoose a option: "))
while 0<opc<7:
if opc == 1:
print("\nchose converter decimal to binary")
print(d_b.converter_decimal_to_binary(int(input("\nenter the decimal number you want to convert: "))))
print("#################################")
opc = int(input("\nchoose a option again please: "))
elif opc == 2:
print("\nchose converter binary to decimal")
print(b_d.converter_binary_to_decimal(input("\nenter the decimal number you want to convert: ")))
print("#################################")
opc = int(input("\nchoose a option again please: "))
elif opc == 3:
print("\nchose converter binary to decimal")
print(t_b.text_binary(input("\nenter the binary you want to convert: ")))
print("#################################")
opc = int(input("\nchoose a option again please: "))
elif opc == 4:
print("\nchose converter binary to decimal")
print(b_t.binary_text(input("\nenter the text you want to convert: ")))
print("#################################")
opc = int(input("\nchoose a option again please: "))
elif opc == 5:
os.system('cls')
#os.system('clear') for linux
menu()
elif opc == 6:
sys.exit()
else:
print("\n¡Invalid option!")
except:
return "EXIT"
menu()
8. By Dace
Made by Dace. ( Source )
x=[]
indicator=-1
a=[]
for z in input('In Decimal that is :'):
x+=z
for y in x:
indicator+=1
r=((len(x)-int(indicator))-1)
s=str(int(y)*(2**r))
a.append(s)
t=str(a).replace("'",'')
u=t.replace('[','')
v=u.replace(',','+')
w=v.replace(']','')
print(eval(w))
9. By ChaoticDawg
Made by ChaoticDawg. Enter a binary representation of a positive integer, Example: 1000100011100111 = 35047. You may also use spaces to separate your bits for readability, Example: 1000 1000 1110 0111. ( Source )
inp = input("Enter a binary number to convert: ").strip().replace(' ', '')
for digit in inp:
if digit not in '01':
raise Exception("Not a binary number")
inp = inp[::-1]
dec = 0
for index, bin in enumerate(inp):
dec += int(bin)*2**index
print(dec)
10. By Minh Trọng
Made by Minh Trọng. ( Source )
def Check(lst):
check = ["0", "1"]
if all(i in check for i in lst):
return True
def ConvertToDecimal(lst):
res = 0
for i in range(len(lst)):
if lst[i] == '1':
res += pow(2, i)
return int(res)
s = input("Enter binary: ")
lst = list(reversed(s))
if Check(lst):
print("\nDecimal of {} is: {}".format(s, ConvertToDecimal(lst)))
else:
print("\nError!")
11. By Benedek Máté Tóth
Made by Benedek Máté Tóth. ( Source )
def binToDec(binarnum):
arr =[]
for i in binarnum:
arr.append(int(i))
bin_list = arr[::-1]
dec=0
power=0
for i in bin_list:
res = i*(2**power)
dec+=res
power +=1
print("%s binary number is equal to %s decimal number" % (binarnum, dec))
binarnum =input("give me a binary number")
binToDec(binarnum)
12. By A H
Made by A H. ( Source )
#Binary to decimal
#Input 101010 = 42
bin_num = list(input())
dec = 0
for r in range(len(bin_num)):
dig = bin_num.pop()
if dig == '1':
dec = dec + pow(2, r)
print("Decimal is: ", dec)
13. By Pranav Kalro
Made by Pranav Kalro. ( Source )
a = str(input())
print("The Decimal number of "+a+": "+str((int(a, 2))))
14. By Issa
Made by Issa. ( Source )
n=input()
for i in n :
assert i=="0" or i=="1", "Binary only."
s=[]
p=len(n) - 1
for i in range(len(n)) :
s.append(int(n[i])*(2**p))
p -= 1
print(sum(s))
15. By luʁi
Made by luʁi. Note: Negative Binaries are not supported. ( Source )
import re
# From Stack Overflow and !necessary tbh.
def raise_(ex):
raise ex
bin2Dec = lambda x: sum([2 ** i for i in range(0, len(str(x))) if str(x)[::-1][i] is "1"]) if re.match(r"^[01]+$", str(x)) else raise_(BaseException("'{0}' is not a valid binary.".format(x)))
print("The decimal of the binary you entered is {0}".format(bin2Dec(input())))
16. By Krishna Modi
Made by Krishna Modi. ( Source )
binary=input("Enter binary no. to convert into decimal:")
print("The decimal representation of the binary is:",int(binary,2))
17. By Kumar
Made by Kumar. ( Source )
b_num = list(input("Input a binary number: "))
value = 0
for i in range(len(b_num)):
digit = b_num.pop()
if digit == '1':
value = value + pow(2, i)
print("The decimal value of the number is", value)
18. By Blazko Reinn
Made by Blazko Reinn. ( Source )
def dec(x):
x = str(x)
x.split()
res = []
co=0
ele = list(range(len(x)))
ele.reverse()
while co<len(ele):
for i in x:
res.append(int(i)*2**ele[co])
co+=1
res=sum(res)
return res
print(dec(int(input())))
19. By Just A Rather Ridiculously Long Username
Made by Just A Rather Ridiculously Long Username. ( Source )
"""
Hit 'RUN' and enter a binary number to convert it to decimal.
P.S.: Just use int(*binary number here*, 2) if you want to convert binary to decimal, this was made just for a demonstration.
"""
def convertBin(x):
x = str(x)
decimal = 0
for i, v in enumerate(x):
if int(v) == 1:
power = len(x) - i -1
decimal += 2**power
elif int(v) > 1:
return "Invalid character '" + v + "', try again"
return decimal
try:
a = int(input())
print(convertBin(a))
except ValueError:
print("Only binary allowed! Try again")
20. By Stefano De Angelis
Made by Stefano De Angelis. ( Source )
#Input a binary number, only 0s and 1s.
def isBinary(binary):
notBinary ="23456789"
notBinaryCount = 0
for i in binary:
if i in notBinary:
notBinaryCount += 1
return notBinaryCount
try:
binary = input()
if binary == "":
0/0
lenBinary = len(binary)
sumBinary = 0
if isBinary(binary) == 0:
for i in range(lenBinary):
sumBinary += (int(binary[lenBinary-i-1])*(2**i))
print(binary, "is equal to", sumBinary)
else:
0/0
except:
print("This is not a binary number!")
#Version: 1.5
#Improved output metod
#The program will no longer accept numbers different from 0 and 1 or non-int object
#Less code
#Fixed a bug
#Created by Stefano de Angelis
#Feel free to copy!
21. By Deeptaksh Gupta
Made by Deeptaksh Gupta. ( Source )
n=int(input())
s=0
while(n>0):
for i in range(len(str(n))):
d=n%10
s+=((2**i)*d)
n=n//10
print(s)
22. By Νεχο
Made by Νεχο. ( Source )
def binary(value):
if ("1" in value and "0" in value):
bits = 1
binary = 0
for i in range(1, len(value)):
bits *= 2
for j in range(len(value)):
if (int(value[j]) == 1):
binary += bits
bits //= 2
else:
bits //= 2
# binary[len(binary) - 1] = ""
# binary[len(binary)] = ""
return str(binary)
else:
return "You can't use any numbers except 0 and 1"
try:
enter_val = str(input())
if (len(enter_val) <= 3):
print("You use unless than 3 the binary numbers retry again.")
else:
print(str(binary(enter_val)))
except:
print("Error compilation code !!!")
print("==========================")
raise
23. By Maisu
Made by Maisu. ( Source )
list = [int(b) for b in list(input()) if (b == "1" or b == "0")]
if len(list) == 0: list = [1, 1, 1]
len = len(list)
binary = ""
decimal = 0
for b in list:
binary += str(b)
len -= 1
decimal += b * (2**len)
print(f"binary to decimal converter \n------------------------------ \nbinary: {binary}\ndecimal: {decimal}\n------------------------------ \nThanks for trying!\nI hope you enjoyed it.\nPlease share, comment and upvote. ")
24. By Martin
Made by Martin. ( Source )
def bin_conv():
num_bin = input()
val_bin = 0
for i in range(len(num_bin)):
if num_bin[-i-1] == "1":
val_bin += 2 ** i
elif num_bin[-i-1] == "0":
val_bin += 0
for j in num_bin:
if j != "0" and j != "1":
is_bin = False
break
else:
is_bin = True
if is_bin == False:
print("Enter a valid binary number.")
else:
print(str(num_bin) + " in binary equals " + str(val_bin) + " in decimal.")
bin_conv()
25. By Zahin Zaman
Made by Zahin Zaman. ( Source )
n=str(input())
x=0
while x<len(n):
if str(n[x])!="1" and str(n[x])!="0":
print("error in input")
x=-1
break
else:
x+=1
if x>0:
x=0
y=int()
i=len(n)-1
while x<len(n):
if str(n[x])=="1":
y+=2**i
i-=1
x+=1
elif str(n[x])=="0":
i-=1
x+=1
print(y)
26. By Jami Bala Manikanta
Made by Jami Bala Manikanta. A basic python program to convert binary number to decimal. ( Source )
d=int(input("enter no:"))
sum=0
i=0
while d>0:
r=d%10
if r==1:
sum=sum+pow(2,i)
d=d//10
i=i+1
print(sum)
27. By Python Learner
Made by Python Learner. ( Source )
bin = input()
dec = 0
if bin.isnumeric():
if any([int(i) > 1 for i in bin]):
print("Please enter binary numbers only!(1,0)")
else:
for i in bin:
dec = dec*2 + int(i)
print(dec)
else:
print("Please enter integers at least!")
28. By nitesh
Made by nitesh. ( Source )
#binary to decimal
import math
n=float(input())
m=str(n)
l=m.split(".")
le=len(l[0])-1
l=l[0]+l[1]
s=0
for i in l:
s+=int(i)*math.pow(2,le)
le-=1
print (s)
29. By PersistentGuy
Made by PersistentGuy. A simple program that takes a Binary as an input and returns a decimal number as Ouput. ( Source )
print('Input your binary: ')
binary = list(input('Binary: '))
i = 0
for num in range (len(binary)):
digit = binary.pop()
if digit == '1':
i = i + pow(2, num)
print('the decimal of your binary', i)
30. By rodwynnejones
Made by rodwynnejones. ( Source )
# input a binary string (1's or 0s) max 20 (so... done be silly)
import re
mylist = [2**x for x in range(20)]
mybinary = input("Type in a number is binary form :-\n")
try:
if len(re.findall(r"[^10]", mybinary)):
raise ValueError
if len(mybinary) > 20:
raise ValueError
except ValueError:
print("An error occurred...")
print("Max (20) input exceeded or")
print("...something other and (one's) 1 and 0 (zeros's) entered.")
exit(1)
sum = 0
for x in range(len(mybinary)):
if mybinary[::-1][x] == '1':
sum += mylist[x]
print(f"Your input > {mybinary} is {sum}")