DEV Community

Lakshyaraj Dash
Lakshyaraj Dash

Posted on

How to convert decimal number to bin, octal and hex format using python ?

In today's article you will see how to convert a decimal number to binary, octal and hexadecimal format.

n = int(input("Enter a number: "))
n1, n2, n3 = n, n, n
temp = n
bin_of_n = ""
while n1!=0:
    rem = n1%2
    bin_of_n += str(rem)
    n1 = n1//2
oct_of_n = ""
while n2!=0:
    rem = n2%8
    oct_of_n += str(rem)
    n2 = n2//8
hex_of_n = ""
dict1 = {
    '10': 'A',
    '11': 'B',
    '12': 'C',
    '13': 'D',
    '14': 'E',
    '15': 'F'
}
while n3!=0:
    rem = n3%16
    if rem > 9 and rem < 16:
        hex_of_n += dict1[str(rem)]
    else:
        hex_of_n += str(rem)
    n3 = n3//16
print(f"Binary form of {temp} is:", bin_of_n[::-1])
print(f"Octal form of {temp} is:", oct_of_n[::-1])
print(f"Hexadecimal form of {temp} is:", hex_of_n[::-1])
Enter fullscreen mode Exit fullscreen mode

Top comments (0)