Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Binary to Decimal Number Converter

Today my professor asked us to do a binary converter using python, and I did it quickly with my friend assigning a variable to the length and decreasing it by 1 in the for loop. And then we decided to do it the opposite way.

We tried to do it converting the number into a list, reversing the list, using the index position to match the required exponent number. But we found 2 main problems with that code:

  • 1.The exponent will never be able to be bigger than 1, because it’s not in the list.
  • 2.The number 1 and 0 are going to repeat a lot of times in the list, so there’s gonna be a problem when we try to access the index value.

Is there any way to fix it or we should just stick to the other method? Here’s the code so you can take a look:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

num = input ('Insert the binary number: ')

res = [int(x) for x in num]
res.reverse()
length = len(res) + 1
counter = 0

for x in range (0, length):
    if res[x] == 1:
        counter += res[x]**res.index(x)
    elif res[x] == 0:
        pass
    else:
        print ('The number is not binary')
        break

print (f'Your number in decimal is : {counter}')

>Solution :

Your method is fine. Two errors in your code:

  1. Do not add 1 to the length as it is already the correct value. If you have a, say, 8 digit binary number the range should be from 0 to 7.
  2. You should simply add 2**x to the counter when the digit is 1. I don’t know why you tried to use the .index()

Here is a working version:

num = input ('Insert the binary number: ')

res = [int(x) for x in num]
res.reverse()
length = len(res)
counter = 0

for x in range(length):
    if res[x] == 1:
        counter += 2 ** x
    elif res[x] == 0:
        pass
    else:
        print ('The number is not binary')
        break

print (f'Your number in binary is : {counter}')

…or a one-liner just for some Python fun:

print(sum(int(x) * 2**i for i, x in enumerate(reversed(num))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading