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.

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]

    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

    Javascript

    function find[decimal_number]

    {

        if [decimal_number == 0]

            return 0;

        else

            return [[decimal_number % 2] + 10 *

                    find[parseInt[decimal_number / 2]]];

    }

    var decimal_number = 10;

    document.write[ find[decimal_number]];

    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

    Chủ Đề