Ask coding questions

← Back to all posts
Python - Need advice for imporving code, binary to decimal converter
prisius (0)

Hello, first of all sorry for my poor english.

I need advice for helping me improve my code.

I am a newbie in python and try to learn but i want to see if there is a way to improve my code without using the built in function for converting binary to decimal.

Thanks in advance to all users.

Answered by malvoliothegood (693) [earned 5 cycles]
View Answer
malvoliothegood (693)

I think what you have done is pretty cool. You could iterate through the binary string backwards like so:

binary_number = '11111'

length = len(binary_number)

def binaryToInteger(number):
  total = 0
  # Start at right-hand end of the binary number string and iterate backwards
  for index in range(length, 0, -1):
    # 1 must be taken off of the number's length as to prevent an out of index error occuring
    # The string value at each index position has to be cast to an integer before
    # maths can be done with it
    total += int(number[index - 1]) * (2**(length - index))

  return total

print(binary_number, 'converted to an int is:', binaryToInteger(binary_number))
prisius (0)

@malvoliothegood Thank you very much. I am still trying to understand how index works in your code and that is a good inspirational code for me. I love the way you've done it. Thank you again for your advice.