Editor

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_to_binary.py
num = 156 # or: num = int(input("Enter a decimal number: "))
# Divide by 2 again and again; the remainders, read backwards, are the binary digits
binary = ""
n = num
while n > 0:
binary = str(n % 2) + binary
n //= 2
if num == 0:
binary = "0"
print("Decimal:", num)
print("Binary (by division):", binary)
print("Binary:", bin(num))
print("Octal:", oct(num))
print("Hexadecimal:", hex(num))
Output
Decimal: 156
Binary (by division): 10011100
Binary: 0b10011100
Octal: 0o234
Hexadecimal: 0x9c

How it works

  1. n % 2 is the remainder when n is divided by 2, which is 0 or 1 and gives the next binary digit from the right.
  2. n //= 2 halves the number, and the loop repeats until nothing is left.
  3. Each new digit is put in front of the string, which reverses the order of the remainders as the method requires.
  4. bin(), oct() and hex() do the conversion in one step and add a prefix, 0b, 0o or 0x, that marks the base.

Other ways to write it

Without the prefixes, using format()

Without the prefixes, using format()
num = 156
print("Binary:", format(num, "b"))
print("Octal:", format(num, "o"))
print("Hexadecimal:", format(num, "X"))
print(f"As an 8-bit byte: {num:08b}")
Output
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

One function for any base
def to_base(n, base):
digits = "0123456789ABCDEF"
if n == 0:
return "0"
result = ""
while n > 0:
result = digits[n % base] + result
n //= base
return result
for base in [2, 8, 16]:
print(f"156 in base {base}: {to_base(156, base)}")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises