Files
Python/BinaryToDecimal.py

35 lines
1.2 KiB
Python
Raw Normal View History

2015-06-14 20:47:28 -07:00
# Python: Binary to Decimal Conversion
# binToDec and decToBin functions are rendered obsolete by the universal convert function
2019-10-01 20:56:50 +05:30
def binToDec(binNum): #function created to convert binary to decimal with parametere binNum
2015-06-14 20:47:28 -07:00
decNum = 0
power = 0
2019-10-01 20:56:50 +05:30
while binNum > 0: #loop will run till binNum is greater than 0
decNum += 2 ** power * (binNum % 10)
binNum //= 10 # reducing binNum everytime by 1 digit
power += 1 # increasing power by 1 each loop
2015-06-14 20:47:28 -07:00
return decNum
2019-10-01 20:56:50 +05:30
def decToBin(decNum): #function created to convert decimal to binary with parametere decNum
2015-06-14 20:47:28 -07:00
binNum = 0
power = 0
2019-10-01 20:56:50 +05:30
while decNum > 0:#loop will run till decNum is greater than 0
2015-06-14 20:47:28 -07:00
binNum += 10 ** power * (decNum % 2)
2019-10-01 20:56:50 +05:30
decNum //= 2 # reducing decNum everytime by 1 digit
power += 1 # increasing power by 1 each loop
2015-06-14 20:47:28 -07:00
return binNum
2019-10-01 20:56:50 +05:30
def convert(fromNum, fromBase, toBase): #function for converting from any base to any other base
2015-06-14 20:47:28 -07:00
toNum = 0
power = 0
while fromNum > 0:
toNum += fromBase ** power * (fromNum % toBase)
fromNum //= toBase
power += 1
return toNum
# print (str(binToDec(101011)))
# print (str(decToBin(128)))
print (str(convert(127, 10, 8))) # converts 127 in base 10 to base 8
2019-10-01 20:56:50 +05:30
print (str(convert(101001, 2, 2)))