Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Beginner · Numbers
Computers store numbers in binary (base 2), which uses only the digits 0 and 1, while octal (base 8) and hexadecimal (base 16, with digits 0 to 9 and then A to F) are shorter ways of writing binary. This program converts a decimal number to binary by repeated division, and then to all three bases with Python built-ins.
Program
Decimal: 156 Binary (by division): 10011100 Binary: 0b10011100 Octal: 0o234 Hexadecimal: 0x9c
How it works
n % 2is the remainder whennis divided by 2, which is 0 or 1 and gives the next binary digit from the right.n //= 2halves the number, and the loop repeats until nothing is left.- Each new digit is put in front of the string, which reverses the order of the remainders as the method requires.
bin(),oct()andhex()do the conversion in one step and add a prefix,0b,0oor0x, that marks the base.
Other ways to write it
Without the prefixes, using format()
Binary: 10011100 Octal: 234 Hexadecimal: 9C As an 8-bit byte: 10011100
The format codes b, o and X give just the digits, and 08b pads the binary with zeros to 8 digits, the way a byte is written.
One function for any base
156 in base 2: 10011100 156 in base 8: 234 156 in base 16: 9C
The same divide-and-keep-the-remainder method works for every base, and the digits string turns a remainder like 12 into the letter C.
Try it yourself
Print a table of the numbers 0 to 16 in decimal, binary, octal and hexadecimal.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises