Why is my Python interpreter interpreting 1s as 0s?
I'm writing a program that converts an integer to binary and everything
has worked well save for one thing. I have the binary numbers stored in a
list, so therefore I want to join the list together using the join()
function. This works well too, however since the list is stored as
integers I must concatenate an empty string with the binary list (whilst
converting each number into a string). By the way, it's nothing to do with
the rest of the code because i've experimented this with a standalone
program and I still get the same results. The code is as follows:
import backwards
class Binary(object):
binary=[1,2,4,8,16,32,64,128,256]
answer=[]
def __init__(self,enter):
self.enter=enter
if self.enter>256:
self.alternative()
elif self.enter<=256:
self.calculate()
def add(self,a,b):
a.append(b)
def clear(self):
Binary.binary=[]
def calculate(self):
start=len(Binary.binary)
start-=1
on=1
off=0
while start>-1:
if self.enter<Binary.binary[start]:
self.add(Binary.answer,off)
start-=1
elif self.enter>=Binary.binary[start]:
self.add(Binary.answer,on)
self.enter-=Binary.binary[start]
start-=1
def alternative(self):
current_max=256
while Binary.binary[len(Binary.binary)-1]<self.enter:
current_max*=2
self.add(Binary.binary,current_max)
self.calculate()
def __str__(self):
converted=""
for i in Binary.answer:
converted+=str(Binary.answer[i])
joined=''.join(converted)
final_answer=backwards.back(joined)
return joined
a=int(input("Enter the decimal number you want to convert to binary: "))
b=Binary(a)
print(b)
The backwards module is a function I created that basically reverses a
string. Basically, THE PROBLEM IS IS THAT if the first two binary numbers
start with a 0, it will print every other 1 as a 0 too (so prints out
00000000). I've purposefully returned the joined variable to prove this
(the final_answer variable just reverses the string like I said). As
mentioned before, it's nothing to do with the rest of the code as I get
the same results when I do this by itself. So how do I make it print out
properly without mysteriously converting 1s to 0s, but at the same time
ensuring that the list is still joined.
No comments:
Post a Comment