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 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 below post. Convert from any base to decimal and vice versa Python provides direct functions for standard base conversions like bin(), hex() and oct()
(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:
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).
This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.