Browse Source

Initial commit

master
Abheek Dhawan 3 years ago
commit
24fd1c460c
Signed by: abheekd GPG Key ID: 7BE81B8C14475B67
  1. 1
      .gitignore
  2. 37
      converter.py
  3. 55
      main.py

1
.gitignore

@ -0,0 +1 @@
__pycache__/

37
converter.py

@ -0,0 +1,37 @@
def decToBin(decIn):
ans = int(decIn)
ret = ""
twoMult = int(1)
currentTwoPwr = int(0)
while ans != 0:
'''
sleep(0.1)
print("TwoMult = " + str(twoMult))
print("ans = " + str(ans))
'''
if (twoMult < ans / 2): # If the current power of 2 is less than half that of the decimal, then double it and increment the power
twoMult *= 2
currentTwoPwr += 1
continue
else:
if twoMult <= ans:
ans -= twoMult
ret += "1"
else:
ret += "0"
currentTwoPwr -= 1
twoMult = 2 ** currentTwoPwr
return int(ret)
def binToDec(binIn):
ans = str(binIn)
ret = 0
currentTwoPwr = 0
for i in reversed(ans):
if (int(i) == 1):
# print("Ret += 2 ** " + str(i))
ret += 2 ** currentTwoPwr
currentTwoPwr += 1
return ret

55
main.py

@ -0,0 +1,55 @@
from converter import decToBin, binToDec
# True: convert from decimal to binary
# False: convert from binary to decimal
convertToBinary = True
print(''' ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ _________ ____ ____ ____ ____ ____ ____ ____ ____ ____
||B |||i |||n |||a |||r |||y |||/ |||D |||e |||c |||i |||m |||a |||l ||| |||C |||o |||n |||v |||e |||r |||t |||e |||r ||
||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||__|||_______|||__|||__|||__|||__|||__|||__|||__|||__|||__||
|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/_______\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|/__\|
''')
print("""Would you like to convert from
1. Decimal to binary
2. Binary to decimal
""")
# Get choice
choiceIn = int(input())
# Get 1 or 2, if neither then keep looping
while True:
match choiceIn:
case 1:
convertToBinary = True
break
case 2:
convertToBinary = False
break
case _:
print("Not a valid choice.")
continue
if (convertToBinary):
print('''
======================================================================
CONVERTING DECIMAL TO BINARY (please separate your inputs with spaces)
======================================================================
''')
decListIn = map(int, input().split(" "))
print ("\n\nOutput:")
for i in decListIn:
print(decToBin(i))
else:
print('''
======================================================================
CONVERTING BINARY TO DECIMAL (please separate your inputs with spaces)
======================================================================
''')
print ("\nOutput:\n")
binListIn = map(str, input().split(" "))
for i in binListIn:
print(binToDec(i))
print("\n\n")
Loading…
Cancel
Save