Python binary converter.

Associate
Joined
6 Jul 2009
Posts
271
Hello trying to learn python and decided to write a small program that will convert 8 digit binary numbers to base 10. Now I know python has a built in function for this and there are a few other ways of doing this but Im trying to figure out what is going wrong in my solution.


Code:
output = 0
data = input("Enter a binary number:")
print (len(data))
print (type(data))
if len(data) < 8 or data.isalpha(): #need to add check for digits that are not 0 or 1
    print("A binary number must be 8 digits long and contain only 1's and 0's")
    
for digit in data:
    if digit == "1":
        if data.index(digit) == (0):
            output = output+128
        elif data.index(digit) == (1):
            output = output+64
        elif data.index(digit) == (2):
            output = output+32
        elif data.index(digit) == (3):
            output = output+16
        elif data.index(digit) == (4):
            output = output+8
        elif data.index(digit) == (5):
            output = output+4
        elif data.index(digit) == (6):
            output = output+2
        elif data.index(digit) == (7):
            output = output+1


print(output)

What I'm trying to achieve is the program goes through the string and checks for a 1 if it finds a 1 then it will add the corresponding value for that index to the total. My code just works if there is only a single 1 in the string but as soon as the is more than 1 it will add 128 for every 1.

Anyone able to point out where I'm going wrong?
 
It's because index gives the first index of the argument so if you have "11000000", the index will always be 0 so give an output of 256 instead of 192 for example

So your for loop should actually be something like

Code:
for digit in  range(0, len(data)):
    if data[digit] == "1":
        if digit == 0:
            output = output+128
        elif digit == 1:
            output = output+64
        elif digit == (2):
            output = output+32
        elif digit == (3):
            output = output+16
        elif digit == (4):
            output = output+8
        elif digit == (5):
            output = output+4
        elif digit == (6):
            output = output+2
        elif digit == (7):
            output = output+1
 
Back
Top Bottom