Convert Decimal to Other Bases in Python
Last Updated :
22 Jun, 2023
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
55 in Hexadecimal : 0x37
Input : 282
Output : 282 in Binary : 0b100011010
282 in Octal : 0o432
282 in Hexadecimal : 0x11a
Convert Decimal to Other Bases Example
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
def decimal_to_binary(dec):
decimal = int (dec)
print (decimal, " in Binary : " , bin (decimal))
def decimal_to_octal(dec):
decimal = int (dec)
print (decimal, "in Octal : " , oct (decimal))
def decimal_to_hexadecimal(dec):
decimal = int (dec)
print (decimal, " in Hexadecimal : " , hex (decimal))
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.
Convert Decimal to Other Bases 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):
binary = "{0:b}" . format (decimal)
octal = "{0:o}" . format (decimal)
hexadecimal = "{0:x}" . format (decimal)
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
55 in hexadecimal: 37
Time complexity: O(1), as the code only performs a constant number of operations (formatting and printing the results).
Auxiliary space: O(1), as the code, only creates a few variables (binary, octal, hexadecimal) that do not depend on the size of the input (the decimal number).
Share your thoughts in the comments
Please Login to comment...