Easy ยท ages 11+ ยท while loop ยท remainder ยท strings
Decimal to binary in Python.
Turn a number into binary by repeatedly dividing by 2.
The program
Press Run to see what it prints. Change anything you like, then run it again.
def to_binary(n):
if n == 0:
return "0"
bits = ""
while n > 0:
bits = str(n % 2) + bits
n = n // 2
return bits
for number in [5, 10, 25, 100, 255]:
print(number, "is", to_binary(number), "in binary")
print("Check:", bin(25), int("11001", 2))5 is 101 in binary 10 is 1010 in binary 25 is 11001 in binary 100 is 1100100 in binary 255 is 11111111 in binary Check: 0b11001 25
How it works
- Binary uses only 0 and 1. Each place is worth twice the one to its right: 1, 2, 4, 8, 16, ...
- To convert, keep dividing by 2. The remainders, read from the last to the first, are the binary digits.
- Python can do it for you with
bin(), andint("11001", 2)turns binary back to a number.
Try this
- Convert your age.
- Write
to_decimalto go the other way. - How many bits does 1000 need?
Stuck on an error? Read how to debug Python.
Similar ideas
More programs
Hello world and variables
Print a message, store things in variables and join them together.
Beginner ยท ages 8+Even or odd
Say whether each number from 1 to 10 is even or odd.
Beginner ยท ages 8+FizzBuzz
Count from 1 to 20. For multiples of 3 print Fizz, for multiples of 5 print Buzz, and for both print FizzBuzz.
Easy ยท ages 9+FAQ
Decimal to binary: questions
What does the decimal to binary program do?
Turn a number into binary by repeatedly dividing by 2. It prints: 5 is 101 in binary / 10 is 1010 in binary / 25 is 11001 in binary โฆ
Which Python ideas does it use?
while loop, remainder, strings. Easy level, suitable from about age 11.
How do I run it?
Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.
What should I try next?
Convert your age. Write to_decimal to go the other way. How many bits does 1000 need?
Start a conversation
Want a teacher to guide the learning?
Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.
- Tell us the learnerโs age or grade and goals
- Weโll suggest a suitable class or learning path
- Weโll confirm format, timing and fees with a parent or guardian
Play it, don't just read it
Write some code right now
Free games that need no sign-up. Pick one and play for five minutes.
Pick a game
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay