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 )
About the Author
Member Avatar masterofpuppets Posting Whiz in Training

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

Finally, see also this link.

>>> 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 :)

If you are curious, also check this out:
http://www.daniweb.com/code/snippet216539.html

thanx man..

Then there is connected discussion aboult long binary numbers for your information in this thread (link directly to my solution)
http://www.daniweb.com/forums/post1219556.html#post1219556