Python Program - Convert Decimal to Binary, Octal and Hexadecimal
httw//:spww.theitroad.com
here's a Python program that converts a decimal number to its binary, octal, and hexadecimal representations:
# get input from user dec = int(input("Enter a decimal number: ")) # convert to binary, octal, and hexadecimal binary = bin(dec) octal = oct(dec) hexadecimal = hex(dec) # print the results print("The binary representation is:", binary) print("The octal representation is:", octal) print("The hexadecimal representation is:", hexadecimal)
In this program, we first use the input()
function to get input from the user, and store it in the variable dec
. We assume that the user enters a valid decimal number, and we convert it to an integer using the int()
function.
We then use the built-in bin()
, oct()
, and hex()
functions to convert the decimal number to its binary, octal, and hexadecimal representations, respectively.
Finally, we use the print()
function to print out the results. Note that the bin()
, oct()
, and hex()
functions return their results as strings that start with a prefix indicating the base of the number (0b
for binary, 0o
for octal, and 0x
for hexadecimal).