Python decimal to binary recursion

Decimal number is converted into binary by dividing the number successively by 2 and printing the remainder in reverse order.

Python decimal to binary recursion

Source Code

# Function to print binary number using recursion
def convertToBinary(n):
   if n > 1:
       convertToBinary(n//2)
   print(n % 2,end = '')

# decimal number
dec = 34

convertToBinary(dec)
print()

Output

100010

You can change the variable dec in the above program and run it to test out for other values.


This program works only for whole numbers. It doesn't work for real numbers having fractional values such as: 25.5, 45.64 and so on. We encourage you to create Python program that converts decimal numbers to binary for all real numbers on your own.

To improve rnbguy's answer, I've found that when your input is any number except 0, it does in fact return the binary representation with an additional '0' in the end.

To remove this the only solution I came up with is to add a global variable that remembers the previous value of the modulo n%2:

prev = 0
def dec2bin(n):
    global prev
    if n < 0:
        return 'Must be a positive integer'
    elif n == 0:
        if prev == 0:
            return '0'
        else:
            prev = 0
            return ''
    else:
        m = n%2
        prev = m
        return dec2bin(n//2) + str(m)

The reason behind this is when you try divmod(0, 2) the output is (0, 0), so we know the output must be a simple'0'. But if we have a number greater than 0, the recursive function will always end dividing 1//2 and 1%2 which will output the same as divmod(1, 2) == (0, 1).

To evade another '0' in the end of our output, we'll save the 1 of 1%2 in the global variable prev and check it when prev != 0 inside the second case since we currently have n = 0.

Before:

>>> print dec2bin(22)
010110
>>> print dec2bin(0)
0

After:

>>> print dec2bin(22)
10110
>>> print dec2bin(0)
0

Notice we have to add prev = 0 alongside return '' or else the print dec2bin(0) will output nothing since the last code executed set the prev to 1.

Source Code:

# Python program to convert decimal number into binary number using recursive function

def binary(n):
   """Function to print binary number
   for the input decimal using recursion"""
   if n > 1:
       binary(n//2)
   print(n % 2,end = '')

# Take decimal number from user
dec = int(input("Enter an integer: "))
binary(dec)

Output:

Enter an integer: 52
110100
Explanation:

In this program, we convert decimal number entered by the user into binary using a recursive function. Decimal number is converted into binary by dividing the number successively by 2 and printing the remainder in reverse order.

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a decimal number as input, we need to write a program to convert the given decimal number into equivalent binary number. 

    Examples : 

    Input : 7                                                         
    Output :111
    
    Input :10
    Output :1010

    We have discussed one iterative solution in below post. 
    Program for Decimal to Binary Conversion
    Below is Recursive solution:

    findBinary(decimal)
       if (decimal == 0)
          binary = 0
       else
          binary = decimal % 2 + 10 * (findBinary(decimal / 2)

    Python decimal to binary recursion

    Step by step process for better understanding of how the algorithm works 
    Let decimal number be 10. 
    Step 1-> 10 % 2 which is equal-too 0 + 10 * ( 10/2 ) % 2 
    Step 2-> 5 % 2 which is equal-too 1 + 10 * ( 5 / 2) % 2
    Step 3-> 2 % 2 which is equal-too 0 + 10 * ( 2 / 2 ) % 2
    Step 4-> 1 % 2 which is equal-too 1 + 10 * ( 1 / 2 ) % 2

    C++

    #include

    using namespace std;

    int find(int decimal_number)

    {

        if (decimal_number == 0)

            return 0;

        else

            return (decimal_number % 2 + 10 *

                    find(decimal_number / 2));

    }

    int main()

    {

        int decimal_number = 10;

        cout << find(decimal_number);

        return 0;

    }

    C

    #include

    int find(int decimal_number)

    {

        if (decimal_number == 0)

            return 0;

        else

            return (decimal_number % 2 + 10 *

                    find(decimal_number / 2));

    }

    int main()

    {

        int decimal_number = 10;

        printf("%d", find(decimal_number));

        return 0;

    }

    Java

    import java.io.*;

    class GFG

    {

        static int find(int decimal_number)

        {

            if (decimal_number == 0)

                return 0;

            else

            return (decimal_number % 2 + 10 *

                    find(decimal_number / 2));

        }

    public static void main(String args[])

    {

        int decimal_number = 10;

        System.out.println(find(decimal_number));

    }

    }

    Python3

    def find( decimal_number ):

        if decimal_number == 0:

            return 0

        else:

            return (decimal_number % 2 + 10 *

                    find(int(decimal_number // 2)))

    decimal_number = 10

    print(find(decimal_number))

    C#

    using System;

    class GFG

    {

        static int find(int decimal_number)

        {

            if (decimal_number == 0)

                return 0;

            else

            return (decimal_number % 2 + 10 *

                    find(decimal_number / 2));

        }

        public static void Main()

        {

            int decimal_number = 10;

            Console.WriteLine(find(decimal_number));

        }

    }

    PHP

    function find($decimal_number)

    {

        if ($decimal_number == 0)

            return 0;

        else

            return ($decimal_number % 2 + 10 *

                    find($decimal_number / 2));

    }

    $decimal_number = 10;

    echo(find($decimal_number));

    ?>

    Javascript

    The above approach works fine unless you want to convert a number greater than 1023 in decimal to binary. The binary of 1024 is 10000000000 (one 1 and ten 0’s) which goes out of the range of int. Even with long long unsigned as return type the highest you can go is 1048575 which is way less than the range of int. An easier but effective approach would be to store the individual digits of the binary number in a vector of bool.

    C++

    #include

    using namespace std;

    void deci_to_bin(int x, string & bin_num)

    {

        if (x <= 1)

            bin_num += (char)(x + '0');

        else {

            deci_to_bin(x / 2, bin_num);

            if(x%2)

              bin_num += '1';

            else

              bin_num += '0';

        }

    }

    int main()

    {

        string bin_num = "";

        deci_to_bin(1048576, bin_num);

        cout<

        return 0;

    }

    Java

    public class Main

    {

        static String bin_num = "";

        static void deci_to_bin(int x)

        {

            if (x <= 1)

                bin_num += (char)(x + '0');

            else {

                deci_to_bin((int)(x / 2));

                if(x%2 != 0)

                  bin_num += '1';

                else

                  bin_num += '0';

            }

        }

        public static void main(String[] args) {

            deci_to_bin(1048576);

            System.out.print(bin_num);

        }

    }

    Python3

    def getbinary(number):

        if number == 0:

            return 0

        smallans = getbinary(number // 2)

        return number % 2 + 10 * smallans

    decimal_number = 1048576

    print(getbinary(decimal_number))

    C#

    using System;

    class GFG {

        static string bin_num = "";

        static void deci_to_bin(int x)

        {

            if (x <= 1)

                bin_num += (char)(x + '0');

            else {

                deci_to_bin((int)(x / 2));

                if(x%2 != 0)

                  bin_num += '1';

                else

                  bin_num += '0';

            }

        }

      static void Main() {

        deci_to_bin(1048576);

        Console.Write(bin_num);

      }

    }

    Javascript

    Output

    100000000000000000000


    How do you convert decimal to binary in Python?

    In Python, we can simply use the bin() function to convert from a decimal value to its corresponding binary value. The bin() takes a value as its argument and returns a binary equivalent. Note: bin() return binary value with the prefix 0b, so depending on the use-case, formatting should be done to remove 0b.

    How do I convert decimal to binary?

    Take decimal number as dividend. Divide this number by 2 (2 is base of binary so divisor here). Store the remainder in an array (it will be either 0 or 1 because of divisor 2). Repeat the above two steps until the number is greater than zero.

    What is binary recursion?

    In binary recursion, the function calls itself twice in each run. As a result, the calculation depends on two results from two different recursive calls to itself. If we look at our Fibonacci sequence generation recursive function, we can easily find that it is a binary recursion.

    How do you convert binary to decimal recursion?

    Recursive Program for Binary to Decimal in C++ The goal is to find the equivalent decimal number using the recursive method. A binary number can be converted to decimal using following method-: Traverse from LSB to MSB and multiply each with power of 2i Where 0<=i<=no. of digits and all previous results to it.