Skip to content
BetaDE
Lesson 1 of 5Exploring computer science

Exploring computer science · Lesson 1 · 35 minutes

Binary numbers, bits and bytes

What you'll learn

  • Understand why computers only calculate with 0 and 1
  • Convert numbers between the decimal and the binary system
  • Know how letters are stored as numbers

Power on, power off

A computer is made of billions of tiny switches. Every switch only knows two states: power on or power off. We write 1 and 0 for that. One such digit is called a bit. Eight bits together are a byte.

With only two digits a computer can still store any number. It uses the binary system for that.

How the binary system works

In the decimal system, every place is worth ten times the place to its right: ones, tens, hundreds. In the binary system, every place is worth twice as much:

Place8421
Digit1101

So 1101 means: 8 + 4 + 0 + 1 = 13. Python converts it for you with int(text, 2) – and with bin() in the other direction:

print(int("1101", 2))
print(bin(13))
print(bin(255))

for number in range(9):
    print(number, "→", bin(number)[2:])

bin() puts a 0b in front so you can see it’s a binary number. With [2:] you cut it off.

How much fits into a byte?

With 8 bits there are 2 · 2 · 2 · 2 · 2 · 2 · 2 · 2 = 256 possibilities: the numbers 0 to 255. Every extra bit doubles the number:

for bits in [1, 2, 4, 8, 16, 32]:
    print(f"{bits:2} bits → {2 ** bits} different values")

That’s why colours on a computer often have values from 0 to 255 – exactly one byte per colour part.

Letters are numbers too

The computer stores every letter as a number. ord() tells you the number, chr() turns it back into a letter:

for character in "Hi!":
    number = ord(character)
    print(character, "→", number, "→", bin(number)[2:])

print(chr(72) + chr(105))

So H is 72 – and the memory holds 1001000. This mapping is called Unicode. You’ll need it soon in the lesson about encryption.

Quick check

What does this program print?

print(int("1010", 2) + int("11", 2))

Your task

Your turn

Write the function to_binary(number). It gets a whole number from 0 upwards and returns it as text made of zeros and ones – without bin() or format(). Here's how: divide the number by 2 again and again. The remainder (% 2) is the next digit from the right each time. Continue with // 2 until the number is 0. Special case: to_binary(0) returns "0".

def to_binary(number):
    result = ""
    # While the number is greater than 0: put the remainder in front, halve the number
    return result


print(to_binary(13))

Solve it without hints to earn a ⭐ on your progress page.

Show solution

Try it yourself first – mistakes teach you the most. Here is one possible solution:

def to_binary(number):
    if number == 0:
        return "0"
    result = ""
    while number > 0:
        result = str(number % 2) + result
        number = number // 2
    return result


print(to_binary(13))