Everything is switches
Your laptop holds billions of tiny switches. Each is either off or on — 0 or 1 — a single bit. Photos, music, this sentence and the code you've written are all just patterns of bits. In this course you'll go from bits to a working CPU you build and program yourself.
Place values in base 2
In decimal, each place is worth 10× the one to its right (1, 10, 100…). In binary each place is worth 2×: 1, 2, 4, 8, 16, 32, 64, 128. 101010 is 32 + 8 + 2 = 42. Eight bits make a byte, which holds 0 to 255.
A row of light switches where the first is worth 1 coin, the next 2, then 4, 8… Any amount up to 255 coins has exactly one switch pattern.
function toBinary(n, width) {
let bits = "";
while (n > 0) {
bits = (n % 2) + bits;
n = Math.floor(n / 2);
}
return bits.padStart(width, "0");
}
function fromBinary(text) {
let value = 0;
for (const bit of text) {
value = value * 2 + (bit === "1" ? 1 : 0);
}
return value;
}