GFG App
Open App
Browser
Continue

# Quickly convert Decimal to other bases in Python

Given a number in decimal number convert it into binary, octal and hexadecimal number. Here is function to convert decimal to binary, decimal to octal and decimal to hexadecimal. Examples:

```Input : 55
Output : 55  in Binary :  0b110111
55 in Octal :  0o67

Input : 282
Output : 282  in Binary :  0b100011010
282 in Octal :  0o432

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

One solution is to use the approach discussed in below post. Convert from any base to decimal and vice versa Python provides direct functions for standard base conversions like bin(), hex() and oct()

## PYTHON

 `# Python program to convert decimal to binary, ` `# octal and hexadecimal `   `# Function to convert decimal to binary ` `def` `decimal_to_binary(dec): ` `    ``decimal ``=` `int``(dec) `   `    ``# Prints equivalent decimal ` `    ``print``(decimal, ``" in Binary : "``, ``bin``(decimal)) `   `# Function to convert decimal to octal ` `def` `decimal_to_octal(dec): ` `    ``decimal ``=` `int``(dec) `   `    ``# Prints equivalent decimal ` `    ``print``(decimal, ``"in Octal : "``, ``oct``(decimal)) `   `# Function to convert decimal to hexadecimal ` `def` `decimal_to_hexadecimal(dec): ` `    ``decimal ``=` `int``(dec) `   `    ``# Prints equivalent decimal ` `    ``print``(decimal, ``" in Hexadecimal : "``, ``hex``(decimal)) `   `# Driver program ` `dec ``=` `32` `decimal_to_binary(dec) ` `decimal_to_octal(dec) ` `decimal_to_hexadecimal(dec) `

Output

```(32, ' in Binary : ', '0b100000')
(32, 'in Octal : ', '040')
(32, ' in Hexadecimal : ', '0x20')```

The time complexity of this program is O(1) as the program only consists of three simple functions and all of them just print values. The space complexity of this program is also O(1) because no extra memory is required to store any values.

#### Using string formatting:

We can use string formatting to convert a decimal number to other bases. Here is an example of how to use string formatting to convert a decimal number to binary, octal, and hexadecimal:

## Python3

 `def` `convert_to_other_bases(decimal):` `    ``# Convert to binary` `    ``binary ``=` `"{0:b}"``.``format``(decimal)` `    `  `    ``# Convert to octal` `    ``octal ``=` `"{0:o}"``.``format``(decimal)` `    `  `    ``# Convert to hexadecimal` `    ``hexadecimal ``=` `"{0:x}"``.``format``(decimal)` `    `  `    ``# Print results` `    ``print``(f``"{decimal} in binary: {binary}"``)` `    ``print``(f``"{decimal} in octal: {octal}"``)` `    ``print``(f``"{decimal} in hexadecimal: {hexadecimal}"``)`   `convert_to_other_bases(``55``)`

Output

```55 in binary: 110111
55 in octal: 67