1

This is a function that is able to take in a binary number as a string and convert it into a decimal number. For some reason, this function always returns None and I can not understand why this is happening. If anyone could provide me with an explanation it would be much appreciated.

total = 0
power = 0
def binaryToDecimal(binaryString):
    global total, power

    n = len(binaryString) - 1

    if n < 0:
        return total
    else:
        if binaryString[n] == '1':
        total += (2 ** power)
    power += 1
    binaryToDecimal(binaryString[:-1])
A. Lewis
  • 67
  • 8
  • 4
    You need a final return statement or a Python function returns `None` if it hit the end... – dawg Nov 06 '16 at 00:53
  • As a certain compiler would say: `Warning: not all paths return`. – Eli Sadoff Nov 06 '16 at 00:55
  • 2
    Another thing you could do is pass `total` and `power` as parameters in your function. It's cleaner than making them `global` in the function definition. – jkr Nov 06 '16 at 00:55
  • By the way, python has built in functions for this. http://stackoverflow.com/questions/8928240/convert-base-2-binary-number-string-to-int – OneCricketeer Nov 06 '16 at 01:06

2 Answers2

1

The final line needs to be return binaryToDecimal(binaryString[:-1]). At the moment you're returning total from the last call, but none of the preceding calls are returning anything.

Batman
  • 8,571
  • 7
  • 41
  • 80
  • Ok, the function now returns an actual number but it is far from correct, is there anywhere else in the code that would cause for the output to be far larger than it should be? – A. Lewis Nov 06 '16 at 01:13
  • For me number produced by your function seems to be correct. You should print the result like `print(binaryToDecimal("1010111001101"))` this should print 5581. – PeterB Nov 06 '16 at 01:21
  • ok, I figured it out, i simply forgot that the use of global variables means that i need to restart the compiler everytime i want to run the code. – A. Lewis Nov 06 '16 at 01:26
0

Instead of recursive call for that, just a for loop like below should do

def binaryToDecimal(binaryString):
    total=0
    # strip of 0b if there is any
    binaryString = binaryString.lstrip('0b')
    n=len(binaryString)
    for i in range(n):
        # index from lsb bit to msb
        if binaryString[n-1-i] == '1':
            total += (2 ** i)
    return total

Alternatively, its recommended to just use python built in int function

def binaryToDecimal(binaryString):
    return int(binaryString, 2)
Skycc
  • 3,496
  • 1
  • 12
  • 18