Python Program to Convert Decimal to Binary, Octal and Hexadecimal

Python program to convert decimal to binary, octal and hexadecimal; Through this tutorial, i am going to show you how to convert decimal to binary, octal and hexadecimal with and without using built-in function in python.

Python Program to Convert Decimal to Binary, Octal and Hexadecimal

See the following python programs to convert decimal to binary, octal and hexadecimal with and without using built-in function:

  • Python Program to Convert Decimal to Binary, Octal and Hexadecimal Using Function.
  • Python Program to Convert Decimal to Binary Using Recursion.
  • Python program to convert decimal to binary using while loop.

Python Program to Convert Decimal to Binary, Octal and Hexadecimal Using Function

In below python program, we have used built-in functions bin()oct() and hex() to convert the given decimal number into respective number systems.

These functions take an integer (in decimal) and return a string.

  • Take a input number from user.
  • Convert decimal integer to binary, octal and hexadecimal using built in functions.
  • Print the result.
# Python program to convert decimal into other number systems
dec = int(input("Enter an integer: "))
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")

Output

Enter an integer:  555
The decimal value of 555 is:
0b1000101011 in binary.
0o1053 in octal.
0x22b in hexadecimal.

Python Program to Convert Decimal to Binary Using Recursion

  • Take input number from user.
  • Define a recursive function to convert demical to binary number.
  • Call this function and print result.
# Python program to convert decimal number into binary number using recursive function
 
def binary(n):
   if n > 1:
       binary(n//2)
   print(n % 2,end = '')
 
# Take input number from user
dec = int(input("Enter an integer: "))
binary(dec)

Output

Enter an integer:  551
1000100111

Python program to convert decimal to binary using while loop

  • Import math module.
  • Take input number from user.
  • Iterate while loop and for loop to convert demical to binary number.
  • Print result.
# python program to convert decimal to binary using while loop
 
import math
 
num=int(input("Enter a Number : "))
rem=""
while num>=1:
    rem+=str(num%2)
    num=math.floor(num/2)
 
binary=""
for i in range(len(rem)-1,-1,-1):
    binary = binary + rem[i]
    
print("The Binary format for given number is {0}".format(binary))

Output

Enter a Number :  50
The Binary format for given number is 110010

Recommended Python Tutorials

Leave a Comment