Binary-to-Decimal and vice-versa

masterofpuppets 0 Tallied Votes 796 Views Share

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

# 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 )
Gribouillis 1,391 Programming Explorer Team Colleague

Also note

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

Finally, see also this link.

Member Avatar for masterofpuppets
masterofpuppets
>>> 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 :)

bumsfeld 413 Nearly a Posting Virtuoso

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

b_nayok 0 Newbie Poster

thanx man..

TrustyTony 888 pyMod Team Colleague Featured Poster

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.