Python Program to convert decimal to octal and hexadecimal

In this simple python program, we need to convert decimal to octal and hexadecimal numbers. It s a conversion python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is the decimal, octal, hexadecimal number system?

In this beginner python program, we have to convert a Decimal number to Octal and Hexadecimal. 

Decimal number system: Decimal is a number with base10 Which means we are using '0 to 9' to represent a number. We are using decimal numbers for all our activities.

Octal number system: Octal number system is a number system with the base 8, which means it uses the numbers from 0 to 7 to represent a number.

How to convert decimal to octal and hexadecimal numbers in python?

We can convert a binary number to an octal by grouping the binary into a group of three. To convert the decimal to octal, we use the successive Euclidean division by 8. This means we divide the number with the highest possible power  8 and then multiply with the highest successively smaller powers of 8.

For example, take a decimal value 125 Then we convert that decimal by using: '125 = 8**2 × 1 + 61 61 = 8**1 × 7 + 5 5 = 8**0 × 5 + 0'.

Hexadecimal Number system: hexadecimal number system is with a base of 16, which means it uses the numbers from zero to nine and the symbols from A to F to represent a number. The hexadecimal number system is mainly used by programmers and designers in the computer programming field.

To convert a decimal to hexadecimal, we need to divide the number by 16 and use the remainder for the hexadecimal value. and convert the '10 to 15' as' A to F'. Repeat that until the quotient is zero.

In this python program, we have to use the inbuilt functions in python to convert from decimal to octal or hexadecimal. To convert the Decimal to Octal, we use the function oct(), and to convert the decimal to hexadecimal, we use hex().

ALGORITHM

STEP 1: Accept the decimal value from the user using input in the python programming language.

STEP 2: Print the octal using the function oct(num).

STEP 3: Print the hexadecimal using the function hex(num).

Python Source Code

                                          num = int(input("Enter a decimal number: "))  
  
print(oct(num),"in octal.")  
print(hex(num),"in hexadecimal.")
                                      

OUTPUT

Enter a decimal number: 20
0o24 in octal.
0x14 in hexadecimal.