Simple functions for binary-to-decimal and decimal-to-binary conversion :)

473 Views
``````# Simple functions to convert from decimal to binary and vice-versa

def toBinary( decimalNumber ):
quotient = 1
remainder = 0
tmpNum = decimalNumber
finalNumberList = []
n = ""

#e.g. take 14...
while quotient != 0:
remainder = decimalNumber % 2 #14 % 2 = 0
quotient = decimalNumber / 2 #14 / 2 = 7
decimalNumber = quotient # 7 % 2 = 1 and so on...
finalNumberList.insert( 0, remainder )

# Used because all numbers are in a list, i.e. convert to string
for num in finalNumberList:
n += str( num )
return n

def toDecimal( binaryNumber ):
multiplier = 0
number = 0
for el in binaryNumber[ : : -1 ]:
number += int( el ) * ( 2**multiplier )
multiplier += 1
return number

print toDecimal( "1110" )
print toBinary( 45 )``````

Hi all I am a second year student in the University of Glasgow so I am still a noobie in programming but I am trying my best sofar and I am happy to help.
So, I am sorry if I make silly mistakes in my programs.

Also note

``````>>> bin(45)  # python >= 3.0
'0b101101'
>>> int('1110', 2)  # python >= 2.5
14``````

``````>>> int('1110', 2)  # python >= 2.5