Python Program to Convert Decimal to Binary, Octal and Hexadecimal

Posted in

Python Program to Convert Decimal to Binary, Octal and Hexadecimal
vinaykhatri

Vinay Khatri
Last updated on March 28, 2024

    There are various number systems in use. Although the decimal number system is the one that is most widely used, we have other number systems like binary, octal , and hexadecimal that we use. Usually, we use these in computers. Here, we will discuss a Python program to convert a decimal value to binary, octal, and hexadecimal values. In this blog post, we have provided Python source code that asks the user to enter a decimal number and then displays its binary, octal and hexadecimal equivalents.

    Prerequisites to Create The Program to Convert Decimal to Binary

    • Python Input/Output
    • Operators in Python
    • Python int()

    In Python, we already have inbuilt functions that can be used to change the base of a value. To represent the different base values in Python, we put the prefix before each value. For instance, the binary values have the 0b prefix, octal uses the 0o prefix, and hexadecimal uses the 0x prefix. For example:

    60 = 0b11100 = 0o74 = 0x3c
    

    Steps

    • First, we will ask the user to enter a decimal number.
    • Using the bin(), oct(), and hex() functions, we will print the binary, octal and hexadecimal values of the decimal number.

    A Python Program to Convert Decimal to Binary, Octal, and Hexadecimal

    Python Code:

    dec_num = int(input("Enter the decimal value: "))
    print(dec_num,"in Binary is:", bin(dec_num))
    print(dec_num,"in Octal is:", oct(dec_num))
    print(dec_num,"in Hexadecimal is:", hex(dec_num))

    Output 1:

    Enter the decimal value: 8
    8 in Binary is: 0b1000
    8 in Octal is: 0o10
    8 in Hexadecimal is: 0x8

    Output 2:

    Enter the decimal value: 16
    16 in Binary is: 0b10000
    16 in Octal is: 0o20
    16 in Hexadecimal is: 0x10

    Conclusion

    There are several instances when you need to convert a decimal number to its binary, octal, or hexadecimal equivalent. The abovementioned program successfully demonstrates how to do so.

    People are also reading:

    Leave a Comment on this Post

    0 Comments