In this article, we’ll look at some programs that translate decimal numbers into their binary equivalents. Two Python programmes will be shown; the first program performs the conversion using a user-defined function, and the second program uses the built-in function bin() for the conversion of decimal to binary. The assignment is to create a Python program that will translate a given decimal number into its 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
# Function to convert decimal number# to binary using recursiondef DecimalToBinary(num):        if num >= 1:        DecimalToBinary(num // 2)    print(num % 2, end = '')# Driver Codeif __name__ == '__main__':        # decimal value    dec_val = 24        # Calling function    DecimalToBinary(dec_val) |
Output
011000
Method #2:Â Decimal to binary using in-built function
- Python3
# Python program to convert decimal to binary  # Function to convert Decimal number# to Binary numberdef decimalToBinary(n):    return bin(n).replace("0b", "")  # Driver codeif __name__ == '__main__':    print(decimalToBinary(8))    print(decimalToBinary(18))    print(decimalToBinary(7)) |
Output
1000 10010 111
Method #3:Without in-built function
- Python3
# Python program to convert decimal to binary  # Function to convert Decimal number# to Binary numberdef decimalToBinary(n):    return "{0:b}".format(int(n))  # Driver codeif __name__ == '__main__':    print(decimalToBinary(8))    print(decimalToBinary(18))    print(decimalToBinary(7)) |
Output
1000 10010 111
Using the bitwise shift operator >>.
- Python3
def dec2bin(number: int):Â Â Â Â ans = ""Â Â Â Â if ( number == 0 ):Â Â Â Â Â Â Â Â return 0Â Â Â Â while ( number ):Â Â Â Â Â Â Â Â ans += str(number&1)Â Â Â Â Â Â Â Â number = number >> 1Â Â Â Â Â Â Â Â ans = ans[::-1]Â Â Â Â return ansdef main():Â Â Â Â number = 60Â Â Â Â print(f"The binary of the number {number} is {dec2bin(number)}")# driver codeif __name__ == "__main__":Â Â Â Â main() |
Output
The binary of the number 60 is 111100
“Get hands-on with our python course – sign up for a free demo!”





