Skip to content

Commit b058df5

Browse files
author
Karan Goel
committed
Binary to decimal done
1 parent b13ede1 commit b058df5

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Numbers/binary_decimal.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Binary to Decimal and Back Converter
3+
Develop a converter to convert a decimal number to binary
4+
or a binary number to its decimal equivalent.
5+
"""
6+
7+
def binary_to_decimal(binary):
8+
"""
9+
Converts a binary number into a decimal number.
10+
"""
11+
decimal = 0
12+
index = 0
13+
while binary > 0:
14+
last = binary % 10
15+
binary = binary / 10
16+
decimal += (last * (2 ** index))
17+
index += 1
18+
return decimal
19+
20+
def decimal_to_binary(decimal):
21+
"""
22+
Converts a decimal number into a binary number.
23+
"""
24+
25+
26+
if __name__ == '__main__':
27+
print """
28+
1. Binary to Decimal
29+
2. Decimal to Binary\n
30+
"""
31+
32+
choice = input("Make a choice: ")
33+
34+
if choice == 1:
35+
binary = input("Binary to convert: ")
36+
print "The binary number %d in decimal is %d" % \
37+
(binary, binary_to_decimal(binary))
38+
elif choice == 2:
39+
decimal = input("Decimal to convert: ")
40+
print "The decimal number %d in binary is %d" % \
41+
(decimal, decimal_to_binary(decimal))
42+
else:
43+
print "Invalid choice"

0 commit comments

Comments
 (0)