Python Program to Convert Decimal to Binary, Octal and Hexadecimal

0



Python Program to Convert Decimal to Binary, Octal and Hexadecimal


In this program, we first take the input of a decimal number from the user using the input() function. The int() function is used to convert the input string to an integer.

We then use the built-in Python functions bin(), oct(), and hex() to convert the decimal number to binary, octal, and hexadecimal respectively.

Finally, we print out the converted values using the print() function

Explanation Of Program :

1.First, we use the input() function to ask the user to enter a decimal number, which is then saved in the decimal_num variable. We use the int() function to change this input value into an integer so that we may subsequently conduct mathematical operations on it.

decimal_num = int(input("Enter a decimal number: "))

2.Using the Python built-in function bin(), we convert the decimal integer to binary. This function converts an integer to its binary representation as a string and accepts an integer as input. In the variable binary_num, we keep the binary string.

binary_num = bin(decimal_num)

3.We employ the built-in Python method oct() to change the decimal number to octal. This method converts an integer to its octal representation as a string and accepts an integer as input. The variable octal_num holds the octal string.

octal_num = oct(decimal_num)

4.Using the Python language's built-in hex() function, we change the decimal number to hexadecimal. The hexadecimal representation of an integer is returned as a string by this function. The variable hexadecimal_num holds the hexadecimal string.

hexadecimal_num = hex(decimal_num)

5.Finally, we print out the converted values using the print() function. We include some text to indicate which number system each value is in.

print("Binary equivalent:", binary_num)
print("Octal equivalent:", octal_num)
print("Hexadecimal equivalent:", hexadecimal_num)

Program of Input  will be :

decimal_num = int(input("Enter a decimal number: "))

# Convert to binary
binary_num = bin(decimal_num)
print("Binary equivalent:", binary_num)

# Convert to octal
octal_num = oct(decimal_num)
print("Octal equivalent:", octal_num)

# Convert to hexadecimal
hexadecimal_num = hex(decimal_num)
print("Hexadecimal equivalent:", hexadecimal_num)

Output of Program :

Enter a decimal number: 45
Binary equivalent: 0b101101
Octal equivalent: 0o55
Hexadecimal equivalent: 0x2d

Post a Comment

0Comments
Post a Comment (0)