Python Program to Convert Decimal to Binary Octal and Hexadecimal

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

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published.