Simple functions for binary-to-decimal and decimal-to-binary conversion :)
Binary-to-Decimal and vice-versa
# 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
masterofpuppets
bumsfeld 413 Nearly a Posting Virtuoso
b_nayok 0 Newbie Poster
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
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.