Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 55 ยท Practice and Review

Practice: Hardware and Data (with Solutions)

Twelve hands-on exercises on units, binary, hexadecimal, two's complement, UTF-8, pixels, cache and storage, each with a runnable editor and a worked solution.

Reading about bits and caches is one thing; being able to work with them is another. This page gives you twelve exercises that cover the first half of the course: data units, number systems, text encoding, images, memory and storage. Each exercise has a short task, an editor with starter code, and a solution you can open once you have tried it yourself.

Here is how to get the most out of them:

  • Estimate first. Before you run anything, guess the size of the answer. Is it closer to 10 or to 10,000? A wrong order of magnitude is the most common mistake in this field.
  • Try before you peek. Spend a few minutes on each exercise. Getting stuck is where the learning happens.
  • Compare, do not copy. Your solution may differ from ours and still be right.

All editors here are stand-ins: they run ordinary JavaScript in your browser to do the arithmetic. The real hardware (a disk, a CPU cache, a display) is not involved; the numbers it works with are.

flowchart LR
  T["Task"] --> E["Estimate the size<br/>of the answer"]
  E --> C["Compute with<br/>a small function"]
  C --> K["Check against<br/>your estimate"]
  K -->|"far off?"| E

A good routine for every exercise: estimate, compute, then sanity-check.

Units and bits

These exercises practice Bits and Bytes.

1. The missing gigabytes

A drive is sold as 2 TB, meaning 2 x 10^12 bytes. Your operating system reports sizes in binary units (GiB, where 1 GiB = 2^30 bytes). Write gibFromTb(tb) and print how many GiB the drive shows.

JS Exercise 1: The missing gigabytes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function gibFromTb(tb) {
  const bytes = tb * 10 ** 12;
  return bytes / 2 ** 30;
}

console.log(gibFromTb(2).toFixed(2), "GiB");

The result is about 1862.65 GiB. Nothing is missing: the seller counts in powers of ten and the system in powers of two. The gap is always about 7 percent at the TB level.

2. How many bits?

A game has 5,000 different item types and wants to give each one a fixed-length binary ID. Write bitsNeeded(count) that returns the minimum number of bits.

JS Exercise 2: How many bits?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function bitsNeeded(count) {
  let bits = 0;
  while (2 ** bits < count) {
    bits++;
  }
  return bits;
}

console.log(bitsNeeded(5000)); // 13
console.log(bitsNeeded(256));  // 8
console.log(bitsNeeded(257));  // 9

13 bits give 8,192 patterns, which is enough; 12 bits give only 4,096. Notice the edge case: 256 values fit exactly in 8 bits, but a 257th value needs a ninth. Math.ceil(Math.log2(count)) is a shortcut, but a loop avoids any rounding surprises.

3. Download time

A file is 4.5 GB (decimal) and your connection runs at 200 Mbps (megabits per second). Ignoring overhead, how many seconds does the download take? Watch the bits-versus-bytes trap.

JS Exercise 3: Download time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function downloadSeconds(fileGB, linkMbps) {
  const bits = fileGB * 1e9 * 8;
  const bitsPerSecond = linkMbps * 1e6;
  return bits / bitsPerSecond;
}

console.log(downloadSeconds(4.5, 200), "seconds"); // 180

4.5 GB is 36 billion bits; at 200 million bits per second that is 180 seconds, or three minutes. Real downloads are somewhat slower because of protocol overhead and shared bandwidth.

Number systems and encoding

These practice Binary, Octal and Hexadecimal and Text and Character Encoding.

4. Binary to decimal by hand

Without using parseInt, convert the binary string "10110110" to a decimal number. Then check your answer against parseInt(text, 2).

JS Exercise 4: Binary to decimal

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function fromBinary(text) {
  let total = 0;
  for (const digit of text) {
    total = total * 2 + Number(digit);
  }
  return total;
}

console.log(fromBinary("10110110")); // 182
console.log(parseInt("10110110", 2)); // 182

The loop uses the "double and add" method: reading left to right, each new digit shifts everything seen so far one place left (times 2) and then adds itself. By position: 128 + 32 + 16 + 4 + 2 = 182.

5. Decimal to hex and binary

Write describe(n) that prints a number in decimal, hexadecimal and binary. Use it on 3054. Then group the binary digits in fours and match each group to a hex digit.

JS Exercise 5: Decimal to hex and binary

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function describe(n) {
  const hex = n.toString(16).toUpperCase();
  const bin = n.toString(2).padStart(12, "0");
  const grouped = bin.match(/.{4}/g).join(" ");
  console.log("decimal:", n);
  console.log("hex:    ", hex);
  console.log("binary: ", grouped);
}

describe(3054);

The output shows BEE and 1011 1110 1110. Each group of four bits is one hex digit: 1011 is B (11), 1110 is E (14). That one-to-four mapping is why programmers love hex.

6. Two's complement and overflow

In 8-bit two's complement, write toTwosComplement(n) that returns the 8-bit pattern of a negative or positive number between -128 and 127. Then add 100 + 100 in 8 bits and see what you get.

JS Exercise 6: Two's complement

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function toTwosComplement(n) {
  const unsigned = n < 0 ? n + 256 : n;
  return unsigned.toString(2).padStart(8, "0");
}

function wrapInt8(n) {
  const low = n & 0xff;          // keep only the low 8 bits
  return low > 127 ? low - 256 : low;
}

console.log(toTwosComplement(-45)); // 11010011
console.log(toTwosComplement(45));  // 00101101
console.log(wrapInt8(100 + 100));   // -56

For -45, flip the bits of 00101101 to get 11010010, then add 1 to get 11010011. The sum 200 does not fit in 8 signed bits (the maximum is 127), so the pattern 11001000 is read as -56. That wrap-around is called overflow.

7. Bytes versus characters

How many bytes does the string "GrรผรŸe ๐ŸŒ" need in UTF-8? How many Unicode code points does it contain, and what does JavaScript's .length say? Predict all three before running.

JS Exercise 7: Bytes versus characters

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
const text = "GrรผรŸe ๐ŸŒ";

const bytes = new TextEncoder().encode(text).length;
const codePoints = [...text].length;

console.log("UTF-8 bytes:", bytes);        // 12
console.log("code points:", codePoints);  // 7
console.log("length:", text.length);      // 8

The letters G, r, e and the space take 1 byte each (4 bytes). The letters รผ and รŸ take 2 bytes each (4 bytes). The globe emoji takes 4 bytes. Total: 12. There are 7 code points. JavaScript strings use UTF-16, where the emoji needs two 16-bit units, so .length is 8. Three different answers to "how long is this string?" is the main lesson of text encoding.

8. Hex color to RGB

Write parseColor("#1e90ff") that returns the red, green and blue values as numbers from 0 to 255. Then count how many distinct colors a 24-bit RGB pixel can show.

JS Exercise 8: Hex color to RGB

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function parseColor(hex) {
  const r = parseInt(hex.slice(1, 3), 16);
  const g = parseInt(hex.slice(3, 5), 16);
  const b = parseInt(hex.slice(5, 7), 16);
  return { r, g, b };
}

console.log(parseColor("#1e90ff")); // { r: 30, g: 144, b: 255 }
console.log(256 ** 3);              // 16777216

Two hex digits are exactly one byte, so a six-digit color is three bytes: 1e is 30, 90 is 144, ff is 255. Three bytes give 256 x 256 x 256 = 16,777,216 colors, often called "16.7 million".

Images, memory and storage

These practice Images, Sound and Video as Data, Memory: RAM, Cache and the Memory Hierarchy and Storage: HDD, SSD and Beyond.

9. Raw video size

A Full HD frame is 1920 x 1080 pixels at 3 bytes per pixel. How large is one uncompressed frame in MB (decimal)? How much data is one second at 30 frames per second?

JS Exercise 9: Raw video size

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function frameBytes(width, height, bytesPerPixel) {
  return width * height * bytesPerPixel;
}

const frame = frameBytes(1920, 1080, 3);
console.log(frame, "bytes per frame");          // 6220800
console.log((frame / 1e6).toFixed(2), "MB");    // 6.22
console.log((frame * 30 / 1e6).toFixed(1), "MB per second"); // 186.6

About 187 MB for one second means an uncompressed hour would need roughly 670 GB. That is why every video you watch is compressed, often by a factor of 100 or more.

10. Average access time

A cache hit costs 1 ns. On a miss the CPU pays the 1 ns lookup plus 100 ns to fetch from RAM. With a 95 percent hit rate, what is the average access time? Then see how fast it gets worse when the hit rate drops to 80 percent.

JS Exercise 10: Average access time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function averageNs(hitRate, hitNs, missPenaltyNs) {
  const missRate = 1 - hitRate;
  return hitNs + missRate * missPenaltyNs;
}

console.log(averageNs(0.95, 1, 100).toFixed(1)); // 6.0
console.log(averageNs(0.80, 1, 100).toFixed(1)); // 21.0

The shortcut is that every access pays the lookup time and only misses pay the penalty. Dropping from 95 to 80 percent hits makes memory access 3.5 times slower on average. This is why cache-friendly code matters so much.

11. Where does element 25 live?

An array of 4-byte integers starts at address 0x1000. Write addressOf(base, index, size) and print the address of element 25 in hexadecimal. Memory is addressed by byte, so think in bytes.

JS Exercise 11: Where does element 25 live?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function addressOf(base, index, size) {
  return base + index * size;
}

console.log("0x" + addressOf(0x1000, 25, 4).toString(16)); // 0x1064

Element 25 starts 25 x 4 = 100 bytes after the base. 100 is 0x64, so the address is 0x1064. This one multiplication is why array access is fast: the computer jumps straight to the spot without scanning.

12. Random reads on disk and SSD

Reading one random file costs about 10 ms on a hard disk (the head must move) and about 0.1 ms on an SSD. How long does it take to read 2,000 small files from each? Then work out the usable capacity of a RAID 5 array of four 4 TB drives (one drive's worth of space holds parity).

JS Exercise 12: Random reads and RAID

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solution
JavaScript
function totalSeconds(reads, msPerRead) {
  return reads * msPerRead / 1000;
}

function raid5Usable(drives, tbEach) {
  return (drives - 1) * tbEach;
}

console.log(totalSeconds(2000, 10));  // 20
console.log(totalSeconds(2000, 0.1)); // 0.2
console.log(raid5Usable(4, 4));       // 12

The hard disk needs 20 seconds and the SSD 0.2 seconds, a factor of 100, because the SSD has no moving parts to wait for. The RAID 5 array holds 12 TB of data out of 16 TB raw; the missing 4 TB buys the ability to survive one failed drive. These timings are typical round numbers, not measurements of a specific product.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A 1 TB drive (10^12 bytes) shows about 931 GiB in your system. What does that tell you?

    Both numbers describe the same number of bytes. 10^12 divided by 2^30 is about 931.
  2. 2. How many bits are needed to give 300 different items unique IDs?

    8 bits give only 256 patterns; 9 bits give 512, which is the smallest power of two that is at least 300.
  3. 3. Which statement about the string "รฉ" in UTF-8 is correct?

    Code points from U+0080 to U+07FF take two bytes in UTF-8, and the precomposed e-acute is U+00E9.
  4. 4. With a 1 ns cache hit and a 100 ns RAM penalty, what happens to the average access time when the hit rate falls from 95% to 80%?

    The average goes from 6 ns to 21 ns because misses are expensive; small drops in hit rate have a big effect.

Summary

  • Always ask which unit is meant: decimal (KB, GB) versus binary (KiB, GiB), and bits versus bytes.
  • n bits give 2^n patterns; round up to find how many bits an ID needs.
  • Hex digits map to groups of four bits; two's complement represents negative numbers and wraps around on overflow.
  • Bytes, code points and JavaScript string length are three different measurements of text.
  • Raw images and video are huge, which is why compression exists.
  • Average memory time depends on the hit rate; address arithmetic is base plus index times size.
  • SSDs win on random access, and RAID trades capacity for fault tolerance.

Continue with Practice: OS, Networks and Security.