# 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 )
>>> int('1110', 2)  # python >= 2.5
14

hahh thanks for that bro. I've actually never tried it before and didn't know it existed.....weird :)

Edited 7 Years Ago by masterofpuppets: n/a

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.