Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Decimal to Binary

Tags:

python

I'm trying to get the function to work, it is suppose to convert Decimal to Binary but all it gives me different numbers instead. Like if I enter 12, it would give me 2. I'm not sure where in the code my issue is located. Any help would be great, thank you!

def decimalToBinary(value):
    if value < 0: #Base case if number is a negative
        return 'Not positive'
    elif value == 0: #Base case if number is zero
        return 0
    else:
        return decimalToBinary(value//2) + (value%2)
like image 911
Element432 Avatar asked Mar 13 '23 03:03

Element432


2 Answers

This may also work

def DecimalToBinary(number):
        #This function uses recursion to convert & print decimal to binary number
       if number > 1:
           convertToBinary(number//2)
       print(number % 2,end = '')

    # decimal number
    decimal = 34

    convertToBinary(decimal)
    #..........................................
    #it will show output as 110100
like image 165
Ihtisham Ali Farooq Avatar answered Mar 23 '23 16:03

Ihtisham Ali Farooq


You faced error because you adding numbers and not iterables but want to get bits sequences...,so you have to convert values you are adding to tuples or strings (or lists), see code below:

def decimalToBinary(value):
    if value < 0: #Base case if number is a negative
        return 'Not positive'
    elif value == 0: #Base case if number is zero
        return (0,)
    else:
         return decimalToBinary(value//2) + (value%2,)

print decimalToBinary(12)

I've replaced (value%2) to (value%2,) to create tuple(, matter, for python it's mean creating a tuple, braces aren't do it... ) and return 0 to return (0,). However you can convert it to string too. For that replace (value%2) to str(value%2 and 0 to str(0).

Note that you can use built-int bin function ti get binary decimal:

 print bin(12) # 'ob1100'

Good luck in your practice !

like image 20
Andriy Ivaneyko Avatar answered Mar 23 '23 15:03

Andriy Ivaneyko