Python Program to Convert Decimal to Binary Octal and Hexadecimal

Python program to convert decimal to binary, octal and hexadecimal; In this tutorial, you will learn 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

  • 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

  • Take a input number from user.
    .medrectangle-4-multi-340{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:auto!important;margin-right:auto!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:250px;padding:0;text-align:center!important;width:100%}

  • 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 Programs

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button