Convert decimal to binary python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a decimal number as input, the task is to write a Python program to convert the given decimal number into an equivalent binary number.
    Examples : 

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

    Method #1: Recursive solution

    DecimalToBinary[num]:
            if num >= 1:
                DecimalToBinary[num // 2]
               print num % 2 

    Below is the implementation of the above recursive solution: 

    Python3

    def DecimalToBinary[num]:

        if num >= 1:

            DecimalToBinary[num // 2]

        print[num % 2, end = '']

    if __name__ == '__main__':

        dec_val = 24

        DecimalToBinary[dec_val]

    Method #2: Decimal to binary using in-built function 

    Python3

    def decimalToBinary[n]:

        return bin[n].replace["0b", ""]

    if __name__ == '__main__':

        print[decimalToBinary[8]]

        print[decimalToBinary[18]]

        print[decimalToBinary[7]]

    Method #3:Without in-built function

    Python3

    def decimalToBinary[n]:

        return "{0:b}".format[int[n]]

    if __name__ == '__main__':

        print[decimalToBinary[8]]

        print[decimalToBinary[18]]

        print[decimalToBinary[7]]

    Quick Ninja Method: One Line Code to Convert Decimal to Binary with user input

    Python3

    or 

    Python3

    decNum = 4785

    print[bin[decNum][2:]]

    decNum1 = 10

    print[bin[decNum1][2:]]

    decNum2 = 345

    print[bin[decNum2][2:]]

    Output

    1001010110001
    1010
    101011001
    


    Learn how to convert decimal to binary in Python.

    Overview

    Base ten digits, ranging from 0 to 9, are used in the decimal or "denary" binary counting system. It is the most widely used system of numbering. Every digit in this system has a place and a decimal point. On the other hand, the binary system employs integers in base two, ranging from 0 to 1. It is the most straightforward system because it has two digits: 0 and 1. As a result, it is common for experts in computer programming or other related engineering fields to need to transform decimal code to binary.

    Scope

    In this article, we’ll learn how to convert Decimal to Binary in Python, using built-in python functions and without it.

    Introduction

    Binary is one of the most important foundational aspects of Computers and other Digital Systems. As we humans use languages to understand and communicate with each other, Computers and other Digital Systems use Binary. It is a base-2 number system with only two numbers, 0 & 1, corresponding to ON & OFF states that your computer can understand.

    As normal humans have ten fingers to represent a simple number system called Decimal, computers have these ON & OFF states representing Binary. So to understand and interpret the Binary, we need some technique to convert binary code into decimal [human-readable] code and vice versa. Thus, this article will discuss how to convert Decimal to Binary and vice versa, in context with one of the computer programming languages, Python.

    Understanding Decimal and Binary

    Decimal System[Base-10] uses ten numbers ranging from 0 to 9 and then uses their combinations to form digits, with each digit being worth ten times more than the last digit [1, 10, 100, so-on] going from left to right.

    Consider a value 265:

    • Here, 265 is a combination of numbers ranging from 0 to 9 to form each digit
    • Each digit is ten times more than the last digit going from left to right 5 -> 5×100; 6 -> 6×101; 2 -> 2×102

    Binary System[Base-2] is also similar. It is a combination of numbers 0 or 1, with each digit worth two times more than the last digit[1, 2, 4, so-on] going from left to right.

    Decimal Digit Representation:

    …[0 to 9][0 to 9][0 to 9][0 to 9][0 to 9]
    10410^4 10310^3 10210^2 10110^1 10010^0
    NthN^{th} digit 5th5^{th} digit 4th4^{th} digit 3rd3^{rd} digit 2nd2^{nd} digit 1st1^{st} digit

    Binary Digit Representation:

    …[0 or 1][0 or 1][0 or 1][0 or 1][0 or 1]
    242^4 232^3 222^2 212^1 202^0
    NthN^{th} digit 5th5^{th} digit 4th4^{th} digit 3rd3^{rd} digit 2nd2^{nd} digit 1st1^{st} digit

    Binary to Decimal Conversion in Python

    We have already seen that the Binary System is a combination of [0 or 1], with each digit worth two times more than the last digit, so let’s see how this information will help us convert binary to decimal equivalent.

    Consider a Binary Number 01011

    Digit01011
    Weight 242^4=16 232^3=8 222^2=4 212^1=2 202^0=1

    Hence,

    [01011]2=[0×24]+[1×23]+[0×22]+[1×21 ]+[1×20]=[0]+[8]+[0]+[2]+[1]=[11]10[01011]^2 = [0×2^4] + [1×2^3] + [0×2^2] + [1×2^1] + [1×2^0] = [0]+[8]+[0]+[2]+[1] =[11]_{10}

    Therefore, the binary[base-2] [01011]2[01011]_2 is equivalent to [11]1 0[11]_{10} Decimal[base-10] number.

    Convert Binary to Decimal in Python

    We will see how to convert binary to Decimal in Python using a built-in function.

    Built-in Function in Python to convert Binary to Decimal:

    In Python, we can use the int[] function to convert a binary to its decimal value. The int[] function takes 2 arguments, a value and the base of the number to be converted, which is 2 in the case of binary numbers

    Syntax:

    Code:

    # Function Binary to Decimal number 
    def binaryToDecimal[val]: 
        return int[val, 2] 
     
    # Driver code 
    if __name__ == '__main__': 
        print[binaryToDecimal['100']] 
        print[binaryToDecimal['101']]
        print[binaryToDecimal['1001']]
    

    Output:

    Decimal to Binary Conversion in Python

    Let’s try to understand the Decimal to binary conversion. The easiest technique to convert the decimal numbers to their binary equivalent is the Division by 2.

    In Division by 2 technique, we continuously divide a decimal number by 2 and note the reminder till we get 1 as our input value. Then we read the noted reminders in reverse order to get the final binary value.

    Let’s break the earlier statements to get more clarity. Assume we have a special function that divides the input number by 2 and gives the remainder as output. For Decimal to Binary, we call this special function multiple times till we get the 1 as the input value. Then, we finally print all the saved reminders to get the final binary[base-2] value.

    Converting Decimal To Binary in Python

    Now we will see how to code the Decimal to Binary in Python. We will first try to code the technique we learned using a custom recursive function call in Python.

    1. Custom Recursive Function in Python to convert Decimal to Binary:

    In this sample, we will write the special function[DecimalToBinary] to implement for obtaining quotients[input to next function call] and the remainder[output value], and then we will call it repeatedly till the input value is greater than and equal to 1

    Code:

    
    #Recursive Function to convert Decimal to Binary
    
    def decimalToBinary[ip_val]:
        if ip_val >= 1:
        # recursive function call
            decimalToBinary[ip_val // 2]
        
        # printing remainder from each function call
        print[ip_val % 2, end = '']
     
    # Driver Code
    if __name__ == '__main__':
        # decimal value
        ip_val = 24
         
        # Calling special function
        decimalToBinary[ip_val]
    

    Output:

    Apart from this, Python also provides a built-in function to convert Decimal to Binary.

    2. Built-in Function in Python to convert Binary to Decimal:

    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.

    Code:

    # Function to convert decimal to binary
    # using built-in python function
    def decimalToBinary[n]:
        # converting decimal to binary
        # and removing the prefix[0b]
        return bin[n].replace["0b", ""]
       
    # Driver code
    if __name__ == '__main__':
        # calling function
        # with decimal argument
        print[decimalToBinary[77]]
    

    Output:

    We can also convert Decimal to Binary in another way apart from using the built-in function from Python.

    3. Without using Built-in Function in Python to convert Binary to Decimal:

    Code:

    # Function to convert Decimal to Binary
    def decimalToBinary[n]:
        return "{0:b}".format[int[n]]
    # Driver code
    if __name__ == '__main__':
        print[decimalToBinary[77]]
    

    Output:

    Conclusion

    1. Most Computers and Digital systems use binary because of their reliable storing of data.
    2. The Decimal system [base-10] uses a combination of numbers from 0 to 9 to form digits, with each digit being worth ten times more than the last digit.
    3. The Binary system [base-2] uses a combination of 0 or 1 to form digits, with each digit being worth two times more than the last digit.
    4. Binary to Decimal conversion is each digit's weighted sum [2i x ith-value].
    5. Binary to Decimal in Python can be performed using the built-in function int[, ]
    6. Decimal to Binary conversion is achieved using the Division By 2 technique.

    Some of the ways to convert Decimal to Binary in Python are by using a custom recursive function, built-in functionbin[] or using “{0:b}”.format[int[]].

    Read More:

    1- How to Convert int to string in Python

    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.

    How do you print binary equivalent in Python?

    Python Program to Print Binary Equivalent of a Number without Using Recursion.
    Take a number from the user..
    Using a while loop, convert each digit into binary and append it to the list..
    Reverse the list and using a for loop print the elements of the list..

    What is bin function in Python?

    The bin[] function returns the binary version of a specified integer. The result will always start with the prefix 0b .

    Chủ Đề