Skip to content
This repository was archived by the owner on Apr 22, 2025. It is now read-only.

Commit c033eaf

Browse files
author
Kalpak Take
authored
Create decimal_to_binary_converter.py
1 parent f47f7f3 commit c033eaf

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

decimal_to_binary_converter.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# For concatenation
2+
def concat(S):
3+
res = ""
4+
for i in S:
5+
if not isinstance(i, str):
6+
res += str(i)
7+
else:
8+
res += i
9+
return res
10+
11+
# Simple Base 10 number(Decimal) number converter to Base 2 number(binary) number
12+
# Function returns answer in str datatype
13+
# For understanding steps: http://www.electronics-tutorials.ws/binary/bin_2.html
14+
def decimal_to_binary(n):
15+
res = []
16+
while n != 0:
17+
res.append(n % 2)
18+
n = n // 2
19+
final = concat(res) + "0"
20+
return final[::-1]
21+
22+
23+
# Test
24+
cases = [123, 23455, 253552, 87985, 3479434, 76, 246572, 231, 69, 2, 7, 2, 543]
25+
for case in cases:
26+
built_in = str(bin(case))[2:]
27+
my_func = decimal_to_binary(case)[1:] # For test purposes
28+
if built_in == my_func:
29+
print("Decimal: " + str(case))
30+
print("Binary: " + my_func + "\nTest Passed!\n")
31+
else:
32+
print("Test Failed! Badly!!\n")

0 commit comments

Comments
 (0)