Write a Python Program to Convert Decimal to Binary, Octal and Hexadecimal

Converting numbers from decimal to binary, octal, and hexadecimal is a fundamental operation in computer programming.

In Python, we can easily perform these conversions using built-in functions.

In this tutorial, we will show you how to convert a decimal number to binary, octal, and hexadecimal in Python.


Converting Decimal to Binary

To convert a decimal number to binary, we can use the bin() function.

The bin() function takes an integer argument and returns its binary representation in the form of a string.

# decimal to binary conversion
decimal_number = 10
binary_number = bin(decimal_number)
print(binary_number)

Output:

0b1010

The prefix “0b” represents that the output is a binary number.

We can remove this prefix using string slicing.

# removing 0b prefix from binary number
binary_number = bin(decimal_number)[2:]
print(binary_number)

Output:

1010

Converting Decimal to Octal

To convert a decimal number to octal, we can use the oct() function.

The oct() function takes an integer argument and returns its octal representation in the form of a string.

# decimal to octal conversion
decimal_number = 10
octal_number = oct(decimal_number)
print(octal_number)

Output:

0o12

The prefix “0o” represents that the output is an octal number.

We can remove this prefix using string slicing.

# removing 0o prefix from octal number
octal_number = oct(decimal_number)[2:]
print(octal_number)

Output:

12

Converting Decimal to Hexadecimal

To convert a decimal number to hexadecimal, we can use the hex() function.

The hex() function takes an integer argument and returns its hexadecimal representation in the form of a string.

# decimal to hexadecimal conversion
decimal_number = 10
hexadecimal_number = hex(decimal_number)
print(hexadecimal_number)

Output:

0xa

The prefix “0x” represents that the output is a hexadecimal number.

We can remove this prefix using string slicing.

# removing 0x prefix from hexadecimal number
hexadecimal_number = hex(decimal_number)[2:]
print(hexadecimal_number)

Output:

a

Conclusion

In this tutorial, we have shown you how to convert a decimal number to binary, octal, and hexadecimal in Python.

We have used the built-in functions bin(), oct(), and hex() to perform the conversions.

You can use these functions to convert any decimal number to its binary, octal, or hexadecimal representation in Python.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.