Python Program to Convert Decimal to Binary, Octal, & Hexadecimal

In number systems, a decimal number (base 10) can be converted into different formats:

  • Binary (base 2) – Used in computers.
  • Octal (base 8) – Sometimes used in computing.
  • Hexadecimal (base 16) – Common in programming and color codes.

In this tutorial, we will write a Python program to convert a decimal number into binary, octal, and hexadecimal using different methods.

Method 1: Using Python’s Built-in Functions

Python provides three built-in functions for number system conversion:

  • bin(n): Converts decimal to binary.
  • oct(n): Converts decimal to octal.
  • hex(n): Converts decimal to hexadecimal.
# Taking user input
num = int(input("Enter a decimal number: "))

# Converting to different number systems
binary = bin(num)   # Binary conversion
octal = oct(num)    # Octal conversion
hexa = hex(num)     # Hexadecimal conversion

# Displaying the results
print(f"Binary of {num} is: {binary}")
print(f"Octal of {num} is: {octal}")
print(f"Hexadecimal of {num} is: {hexa}")

Output

Enter a decimal number: 25
Binary of 25 is: 0b11001
Octal of 25 is: 0o31
Hexadecimal of 25 is: 0x19

Prefix Explanation:

  • 0b β†’ Binary
  • 0o β†’ Octal
  • 0x β†’ Hexadecimal

Method 2: Using Custom Functions (Without Built-in Functions)

To convert manually, we can use loops and division by 2 (binary), 8 (octal), and 16 (hexadecimal).

# Function to convert decimal to binary
def decimal_to_binary(n):
    binary = ""
    while n > 0:
        binary = str(n % 2) + binary
        n //= 2
    return binary or "0"

# Function to convert decimal to octal
def decimal_to_octal(n):
    octal = ""
    while n > 0:
        octal = str(n % 8) + octal
        n //= 8
    return octal or "0"

# Function to convert decimal to hexadecimal
def decimal_to_hexadecimal(n):
    hex_digits = "0123456789ABCDEF"
    hexa = ""
    while n > 0:
        hexa = hex_digits[n % 16] + hexa
        n //= 16
    return hexa or "0"

# Taking user input
num = int(input("Enter a decimal number: "))

# Converting and displaying results
print(f"Binary of {num} is: {decimal_to_binary(num)}")
print(f"Octal of {num} is: {decimal_to_octal(num)}")
print(f"Hexadecimal of {num} is: {decimal_to_hexadecimal(num)}")

Output

Enter a decimal number: 50
Binary of 50 is: 110010
Octal of 50 is: 62
Hexadecimal of 50 is: 32
Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Β 194