How to convert decimal number to bin, octal and hex format using python ?
Lakshyaraj Dash
Posted on October 20, 2022
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])
💖 💪 🙅 🚩
Lakshyaraj Dash
Posted on October 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev 🎉 Dive into Python 3.13: New Features, JIT Compiler, Free threading & Installation Guide! 🎉
November 12, 2024