Skip to content
Advertisement

How to convert from decimal to a binary string?

The goal of this part of the lab is to motivate a right-to-left conversion of decimal numbers into binary form. Thus, you will end up writing a function numToBinary(anInteger) that works as follows:

>>> numToBinary(5)
'101'

The code I have is:

def isOdd (x):
    if x%2==1:
        return('True')
    if x%2==0:
        return('False')

def numToBinary(x):
    if n==0:
        return ''
    elif isOdd(x):
        return numToBinary(x//2)+'1'
    else:
        return numToBinary(x//2)+'0'

But this returns the string from left to right. Can anyone help me find a way to go from the left to right representation to a right to left representation?

Advertisement

Answer

Is this Python?

I don’t see any “left-to-right” problem in your code. However, the function isOdd that you provided returns Strings ('False' and 'True'). It should return Booleans (i.e. remove the single-quotes).

def isOdd (x):
    if x%2==1:
        return(True)  # <<< THIS
    if x%2==0:
        return(False) # <<< AND THIS

Also, you’re using a variable named n inside numToBinary, which is not defined anywhere (it should be x, obviously)

def numToBinary(x):
    if x==0:          # <<<< THIS!
        return ''
    elif isOdd(x):
        return numToBinary(x//2)+'1'
    else:
        return numToBinary(x//2)+'0'

This code should work fine.

If you just want to convert a number to binary, you can use Python’s internal bin function. Try: bin(5)[2:] for example.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement