Why 0 and 1?
Inside a computer, tiny electronic switches are either off or on. It is very reliable to tell two states apart, so computers use base 2 (binary), which has only two digits: 0 and 1. Each binary digit is a bit.
Place values
In decimal each place is worth ten times the one to its right (1, 10, 100…). In binary each place is worth two times as much:
place: 128 64 32 16 8 4 2 1
binary: 0 0 1 0 1 1 0 1
value: 32 + 8 + 4 + 1 = 45
So 00101101 in binary is 45 in decimal.
Decimal to binary
Divide by 2 repeatedly and write down the remainders, then read them from bottom to top. For 13:
13 ÷ 2 = 6 remainder 1
6 ÷ 2 = 3 remainder 0
3 ÷ 2 = 1 remainder 1
1 ÷ 2 = 0 remainder 1
reading upwards: 1101
Check it with Python:
print(bin(13)) # 0b1101
print(int("1101", 2)) # 13
print(int("00101101", 2)) # 45
print(format(45, "08b")) # 00101101Bits and bytes
8 bits make a byte, which can hold 28 = 256 different values (0 to 255). That is why colours in CSS go from 0 to 255 for each of red, green and blue, and why #ff0000 (255 red, 0 green, 0 blue) is pure red: ff is 255 written in hexadecimal (base 16).
A kilobyte is about a thousand bytes, a megabyte about a million and a gigabyte about a billion.
How text is stored
Each character has a number. In Unicode, "A" is 65 and "a" is 97. UTF-8, the encoding used by most of the web, stores common English characters in one byte and others, such as ë or emoji, in two to four bytes:
print(ord("A")) # 65
print(chr(97)) # a
print(format(ord("A"), "08b")) # 01000001
print(len("ë".encode("utf-8"))) # 2 bytesTry it yourself
Convert 7, 64 and 200 to binary by hand, then check them with Python in Unays Code. Challenge: write your own function that converts a number to binary using the divide-by-2 method, without using bin().
This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].