You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
1000 B
37 lines
1000 B
3 years ago
|
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
|