+

Quickly convert decimal to other bases in Python

Examples:

 Input: 55 Output: 55 in Binary: 0b110111 55 in Octal: 0o67 55 in Hexadecimal: 0x37 Input: 282 Output: 282 in Binary: 0b100011010 282 in Octal: 0o432 282 in Hexadecimal : 0x11a 

One solution is to use the approach discussed in the post below.

Convert from any base to decimal and vice versa

Python provides direct functions for standard base conversions like bin (), hex () and oct ()

# Python program to convert decimal to binary
# octal and hex

 
# Function to convert decimal to binary

def decimal_to_binary (dec):

  decimal = int (dec)

  

  # Print the equivalent decimal number

print (decimal, " in Binary: " , bin (decimal))

 
# Function to convert decimal to octal

def decimal_to_octal (dec):

decimal = int (dec)

  

# Print an equivalent decimal number

print (decimal, "in Octal:" , oct (decimal))

  
# Function to convert decimal to hex

def decimal_to_hexadecimal (dec):

decimal = int (dec)

 

# Print the equivalent decimal number

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: 0o40 32 in Hexadecimal: 0x20 

This article is provided by Pramod Kumar . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

Get Solution for free from DataCamp guru