I am working on a program for my Fundamental Structures class where I have to ad
ID: 3621683 • Letter: I
Question
I am working on a program for my Fundamental Structures class where I have to add two binary numbers in Python. In order to this, we're supposed to Convert the binary number to a string, and then interpret the numbers individually and convert it to Decimal, add the two decimal numbers, then convert it back to binary after.I've been trying to research this, but being new to Python, and having not done any programming in a while, I cannot figure it out. How can I convert a binary number into decimal and add them without using any of the predefine functions in Python?
Thanks.
Explanation / Answer
#! /usr/bin/python
"""Converts a decimal number to binary, or more accurately a list of bool,
I.E.: 101001 would become:
[True,False,True,False,False,True]
([1,0,1,0,0,1])"""
def bin2dec(bin):
"""Converts a binary list to decimal number"""
dec = 0
#reverse list:
rev_bin = []
for item in bin:
rev_bin.insert(0,item)
#calculate decimal
for index in xrange(len(bin)):
dec += rev_bin[index] * 2**index
return dec
def dec2bin(dec):
"""Converts a decimal number to a binary list"""
bin = []
#find the largest power that goes into dec
Continue = True
powers = 0
while Continue == True:
if dec > 2**powers:
powers += 1
else:
Continue = False
powers += 1
#find each bin digit
for power in xrange(powers,0,-1):
if dec >= 2**(power-1):
dec -= 2**(power-1)
bin.append(True)
else:
bin.append(False)
#removes all Falses at the begining
while bin[0] == False:
del bin[0]
return bin
def bin2txtrepr(bin):
"""Converts a binary list to inary "text"
I.E.: [True,True,False] would become:
'110'"""
txtbin = ""
for bit in bin:
if bit == True:
txtbin += '1'
else:
txtbin += '0'
return txtbin
print bin2txtrepr(dec2bin(25))
print bin2dec(dec2bin(25))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.