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!”






