Course outline · 0% complete

0/28 lessons0%

Course overview →

Binary and bytes

lesson 2-1 · ~11 min · 4/28

Quiz

Warm-up from lesson 1-2: your tiny CPU simulator stored the program as a list called memory and read memory[pc] each cycle. In a real computer, where does that program live while it runs?

Everything is bits

Why spend a unit on this? Because file sizes, network payloads, corrupted text, and the famous 0.1 + 0.2 surprise in the next lesson are all consequences of one fact engineers hit weekly: the machine stores nothing but bits, and every meaning is a rule we layer on top.

RAM, disk, and the CPU all store exactly one kind of thing: bits. A bit is a single 0 or 1, physically a tiny switch that is off or on. A byte is a group of 8 bits.

Numbers, text, images, and code are all patterns of bits. The pattern only means something because we agree on a rule for reading it. The rule for whole numbers is binary, which is ordinary place-value counting with 2 instead of 10.

In decimal, 203 means 2×100 + 0×10 + 3×1. In binary, 101 means 1×4 + 0×2 + 1×1 = 5. Each place is worth double the one to its right: 1, 2, 4, 8, 16, 32, 64, 128.

12864321684210010101032 + 8 + 2 = 42one byte = 8 bits
The byte 00101010. Adding the place values of the 1-bits (gold) gives 42.

Code exercise · python

Run this. bin() shows a number's binary form (the 0b prefix just marks it as binary), and int(text, 2) converts binary text back to a number.

Code exercise · python

Your turn. Print the binary form of 42, then convert the binary text "101010" back into a number. You should see 0b101010 and then 42.

Hexadecimal: the shorthand for bytes

Binary is what the machine stores, but eight 0s and 1s per byte is miserable for humans to read, so programmers write bytes in hexadecimal (hex): place-value counting in base 16, using the digits 0-9 and then a-f (a=10, b=11, ... f=15). The reason hex won is exact fit: one hex digit represents exactly 4 bits, so one byte is always exactly two hex digits. ff is 255, the largest byte value.

You will meet hex everywhere bytes are shown: 0xff in code, #d4af37 in web colors (three bytes: red, green, blue), memory addresses in crash reports, and byte dumps like \xc3\xa9 in the next lesson. Python marks hex numbers with the 0x prefix, the same way 0b marks binary.

Code exercise · python

Run this. hex() shows a number's hexadecimal form, int(text, 16) converts hex text back to a number, and 0xc3 is a hex literal you can compute with directly.

Quiz

One byte is 8 bits. How many different values can it represent?