Bits, bytes and binary numbers
Every number in a computer is a row of bits. Toggle eight bits, watch their place values add up, and convert between decimal and binary digit by digit.
The idea
A byte is eight switches. Each one is on (1) or off (0).
Numbers, letters and pictures are all stored as rows of switches like this one.
Intuition
Each bit has a place value. It doubles from right to left: 1, 2, 4, 8, up to 128.
A bit that is on adds its place value. 8 + 4 + 1 makes 13, so 13 is 00001101.
Eight bits give 256 patterns, so values from 0 to 255.
n bits give 2^n patterns. The largest value is 2^n - 1, because 0 uses one pattern.
Complexity
The loop runs once per bit. Doubling the value adds only one bit, so the cost is O(log n).
A value near one million needs 20 bits, so 20 passes. Space is one row of bits.
Pitfalls
Bit 0 is the rightmost bit and is worth 1, so 00000001 is 1. Reading from the left would give 128.
200 + 100 = 300 needs 9 bits. A byte keeps only the low 8 bits, so it wraps around to 44.
Hardware drops the carry out of the top bit. This is called overflow.
Variations
Counting the 1s gives the set bits. 180 has four of them.
Code
Pseudocode
bits ← width zeros, left ← n
for k from width - 1 down to 0
place ← 2^k
if place ≤ left
bits[k] ← 1, left ← left - place
else bits[k] ← 0
return bits
Python
def to_bits(n, width):
bits = [0] * width
left = n
for k in range(width - 1, -1, -1):
place = 2 ** k
if place <= left:
bits[k] = 1
left -= place
else:
bits[k] = 0
return bits
JavaScript
function toBits(n, width) {
const bits = new Array(width).fill(0);
let left = n;
for (let k = width - 1; k >= 0; k--) {
const place = 2 ** k;
if (place <= left) {
bits[k] = 1;
left -= place;
} else {
bits[k] = 0;
}
}
return bits;
}
Practice problems (9)
Convert 13 to binary Warm-up
Write 13 as a binary number. Use the place values 8, 4, 2 and 1.
Read a byte Warm-up
What decimal number does this byte show? Add the place values of the bits that are on.
Largest value in n bits Warm-up
What is the largest unsigned value that 10 bits can hold?
Count set bits Standard
How many bits are set to 1 in this byte?
Follow the conversion of 11 Standard
Watch 11 become bits, one place value at a time, and answer the prompts.
Count the 1 bits of a number Standard
Return how many bits are 1 in the binary form of n. Check one bit at a time.
Write a number in binary Standard
Return the binary form of n as a string, with no leading zeros. Zero is "0".
Add two binary numbers by hand Challenge
Add the two bytes column by column from the right. Write the sum as 8 bits.
Add two binary strings Challenge
a and b are binary numbers written as strings. Return their sum as a binary string.
Work from the right and keep a carry, as in the lesson.
Next on the path: Big-O, Big-Θ and Big-Ω