On this concept: Formula

Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Computational Thinking · Grade 6-8

Data Compression

Data compression is the process of reducing the number of bits needed to store or transmit information.

compression ratio=original sizecompressed size

Quick Answer

Data compression is the process of reducing the number of bits needed to store or transmit information. You use it whenever a file is too big to keep or too slow to send: zipping a folder for email, saving a photo as JPEG, streaming music to a phone. Lossless compression (ZIP, PNG) finds repetition and writes it more briefly, so every bit comes back. Lossy compression (JPEG, MP3) also throws away detail people barely notice, which shrinks files much further but cannot be undone.

Why This Matters

A 3-minute song stored as CD audio takes about 32 MB; as an MP3 it takes about 3 MB, which is why a phone holds thousands of songs and a video call fits through home internet. Knowing which kind of compression you are using tells you what is safe: you can zip and unzip a document forever, but every re-save of a JPEG loses a little more.

Intuitive Explanation

Look at one row of a black-and-white picture: WWWWWWWWWWBBBBBWWWWW, 20 pixels. Instead of writing every pixel, write the runs: 10 white, 5 black, 5 white. Anyone who knows the rule can rebuild the row exactly, pixel for pixel. That is run-length encoding, a simple lossless method. It works because the row repeats itself, and repetition is what every lossless method hunts for: repeated letters, repeated words, large patches of one colour.

Lossy compression goes further. A photo of the sky contains thousands of slightly different blues. JPEG rounds many of them to the same value and stores fine detail coarsely, because your eye hardly notices. The file can shrink to a tenth of its size, but the rounded-away values are gone. Save the result as a JPEG again and it rounds again, so quality drops a little with each save.

Not every way of shrinking a file is compression. Cropping a photo or deleting pages from a document makes the file smaller by removing content, not by storing the same content in fewer bits. There is also a limit: data with no pattern, such as a file that is already zipped, has little repetition left, so zipping it a second time barely changes its size.

Think of it like this. Compression is packing a suitcase. Lossless is rolling and folding: everything you packed comes out again, just in less space. Lossy is leaving things at home that you probably will not miss; the bag gets much lighter, but those things are not there when you unpack.

Core idea. Compression trades storage and transfer speed against exactness or quality.


When to Use

Think compression when a problem is about file size, storage space, upload time or bandwidth, or asks whether the original can be restored. If every bit must come back (text, program code, spreadsheets, bank records), choose lossless. If a smaller file matters more than perfect detail (photos, music, video), lossy is acceptable. If the question is about hiding data from other people, that is encryption; if it is about how a letter or pixel becomes bits in the first place, that is data representation.

Tip. Ask: Is the same information being stored in fewer bits, either recoverable exactly or with some detail thrown away?

How to Recognize It

Compare the file before and after: compression keeps the same content but writes it in fewer bits.

  1. Is the file smaller afterwards while still holding the same picture, song or text?

    Yes is compression. If it is smaller because content was cut, like cropping a photo or deleting pages, nothing was compressed; the data itself changed.

  2. Must every bit come back exactly when the file is opened?

    Yes requires lossless compression, such as ZIP or PNG. If small losses are acceptable, as with photos or music, lossy formats like JPEG and MP3 shrink it much further.

  3. Can anyone with the right program open the result, with no secret needed?

    Yes fits compression. If the goal is that only someone with a key can read it, and the size barely changes, it is Encryption.

  4. Is the question about making data smaller, not how it became bits in the first place?

    Yes keeps you at compression. If it asks how a letter or a color becomes a pattern of bits at all, it is Data Representation.

Data Compression vs Encryption vs Data Representation vs Image Representation

Compression, encryption and encoding all rewrite data as different bits, and images are where most people meet compression. Ask whether the rewrite makes data smaller, secret, or readable as bits in the first place.

Data Compression

Meaning
Data compression rewrites data in fewer bits, either so it can be restored exactly or by dropping detail people barely notice.
Key test
The point is a smaller file; anyone with the format can open it.
Formula
compression ratio=size beforesize after
Example
A 10 MB folder zipped to 4 MB has a ratio of 2.5, and unzips to the exact files.

Encryption

Meaning
Encryption turns readable data into scrambled data that only someone holding the right key can turn back.
Key test
The point is secrecy; the size stays about the same.
Example
A password manager keeps your passwords encrypted, so a stolen copy is unreadable without your main password.

Data Representation

Meaning
Data representation is the agreed code that turns text, numbers, colors and sound into bits at all.
Key test
It answers what the bits mean, before any shrinking or hiding.
Formula
E:D→{0,1}∗
Example
The letter 'B' is stored as 66, which is 01000010 in binary.

Image Representation

Meaning
Image representation describes a picture as rows of pixels, each holding red, green and blue values.
Key test
It gives the raw size before any format shrinks it.
Formula
bytes=w×h×3
Example
A 1,000 by 1,000 photo at 3 bytes per pixel is 3 MB before compression.

Formula & Notation

compression ratio=original sizecompressed size
Compression maps a source message to a shorter code representation. Lossless methods preserve exact decoding; lossy methods accept some distortion to reduce size further.

Worked Examples

Example 1 — Run-length encode a pixel row

Easy

A row of 24 black-and-white pixels reads WWWWWWWWWWWWBBBBBBWWWWWW (12 white, 6 black, 6 white). Stored plainly, each pixel takes 1 bit. A run-length code stores each run as a 1-bit colour plus a 4-bit count (counts up to 15). Compress the row, find its size in bits, and give the compression ratio.
Show the steps and the answer
  1. Split the row into runs: 12 W, 6 B, 6 W.

    Run-length encoding replaces each stretch of one colour with that colour and the length of the stretch.

  2. Encode each run in 5 bits (1 colour bit + 4 count bits): 3 runs × 5 bits = 15 bits.

    Both counts fit in 4 bits (12 is 1100, 6 is 0110), so every run costs the same 5 bits.

  3. Compute the ratio: 24 ÷ 15 = 1.6.

    Compression ratio is original size over compressed size, so the row now needs 15/24 = 62.5% of its old space.

  4. Decode to check: 12 W, 6 B, 6 W rebuilds all 24 pixels in order.

    Nothing was rounded or dropped, so this method is lossless.

Answer: 15 bits instead of 24: a compression ratio of 1.6, and the row needs 62.5% of its original space.

Takeaway: Run-length encoding saves space when data has long runs of the same value, and decoding gives back every bit.

Example 2 — When compression makes a file bigger

Standard

Use the same code (5 bits per run) on the 12-pixel row WBWBWBWBWBWB, where the colours alternate. What happens to the size?
Show the steps and the answer
  1. Count the runs: every pixel starts a new run, so there are 12 runs of length 1.

    Run-length encoding only helps when neighbouring values repeat, and here no two neighbours match.

  2. Compute the size: 12 runs × 5 bits = 60 bits, against 12 bits stored plainly.

    Each 1-bit pixel now drags 4 extra count bits along with it.

  3. Compute the ratio: 12 ÷ 60 = 0.2.

    A ratio below 1 means the 'compressed' version is larger than the original, here five times larger.

  4. Store this row plainly, or use a method that looks for a repeated pattern (WB appears 6 times) instead of runs.

    No lossless method can shrink every possible input; each one shortens only the kind of pattern it is built to find.

Answer: 60 bits instead of 12: a ratio of 0.2, so the row grows to five times its size. Keep it uncompressed.

Takeaway: Compression pays only when the data contains the kind of repetition the method can see; check for long runs before choosing run-length encoding.

Example 3 — Find the mistake: is the JPEG the original?

Application

An uncompressed 4,000 KB photo is saved as a 400 KB JPEG. Lena writes: "The compression ratio is 4,000 ÷ 400 = 10, so the JPEG holds the same picture in a tenth of the space. I can delete the original and open the JPEG to get it back exactly." Find the mistake and correct it.
Show the steps and the answer
  1. Check the ratio: 4,000 KB ÷ 400 KB = 10.

    The arithmetic is right; the error is in what Lena believes the JPEG contains.

  2. Name the method: JPEG is lossy.

    To reach a ratio of 10, JPEG rounds colour values and stores fine detail coarsely, and the rounded-away values are not kept anywhere in the file.

  3. Decide what opening the JPEG gives: a full-size picture rebuilt from the kept values, close to the original but not the same pixels.

    Decoding cannot restore information that was discarded, and every later re-save as JPEG discards a little more.

  4. Fix the plan: keep the original, or store a lossless copy such as PNG if exact pixels matter.

    Only lossless formats guarantee every bit back; for a photo they shrink the file far less than 10 times, which shows how much detail paid for JPEG's saving.

Answer: The ratio of 10 is correct, but JPEG is lossy, so the original cannot be recovered exactly. Keep the 4,000 KB original (or a lossless PNG copy) if the exact image matters.

Takeaway: Before deleting an original, check whether the format is lossless (ZIP, PNG) or lossy (JPEG, MP3); only lossless gives every bit back.

Where You'll See It

  • Zipping a folder to email it

    A ZIP file uses lossless compression to shrink documents so they fit an email limit, and unzipping restores every byte exactly — perfect for files where losing data would be a disaster.

  • Saving a photo as JPEG

    JPEG uses lossy compression: it throws away detail your eye barely notices to make the file much smaller — great for sharing, but re-saving repeatedly slowly degrades the image.

  • Streaming music at different qualities

    A streaming app offers 'high' and 'data saver' modes — the lower mode compresses more (lossy), trading some audio detail for a smaller, faster stream, showing the storage-vs-quality trade-off.

Common Mistakes

  1. The slip: All compression can be perfectly reversed to get the original back.

    Why it's tempting: Unzipping a ZIP gives the exact files back, so students assume every format works that way.

    Instead: Only LOSSLESS compression recovers the original exactly. LOSSY compression (JPEG, MP3) permanently discards detail to save more space — you can never get the lost data back.

  2. The slip: Re-compressing a lossy file again is harmless.

    Why it's tempting: Each save still looks 'fine,' so repeating it seems free.

    Instead: Every lossy re-save discards more detail (generation loss), so repeatedly saving a JPEG or re-encoding an MP3 visibly or audibly degrades quality over time.

  3. The slip: Whichever compressed file is smaller used the better compression method.

    Why it's tempting: Compression is about saving space, so the smallest file looks like the obvious winner.

    Instead: Check the format and settings first: a JPEG of a photo saved at low quality is smaller than a PNG of the same photo because it threw detail away, while the PNG keeps every pixel. Compare methods only on the same input and the same kind of setting, both lossless or both lossy at the same quality.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. Use run-length encoding on AAAABBBCCD, writing each run as a count then a letter. What is the code, and what is the compression ratio in characters?

    Hint: Count each run of the same letter. Ratio = original size ÷ compressed size.

  2. A 12 MB file compresses to 3 MB. What is the compression ratio, and what percentage of the size was saved?

    Hint: Divide original by compressed. Then find how much of the 12 MB was removed.

  3. Run-length encode ABABABAB, using a count then a letter for each run. Did the data get smaller?

    Hint: Each run here is only one letter long.

  4. A row of pixels is stored as 3W2B4W, where W is white and B is black. Decode it. How many pixels are in the row?

    Hint: Each number says how many times the next letter repeats.

  5. Copy 1 of a 1000 × 1000 photo is resized to 500 × 500, and its file shrinks to a quarter. Copy 2 keeps 1000 × 1000 pixels but is saved as JPEG and also shrinks to a quarter. Which change is data compression?

    Hint: In which copy did the number of pixels stay the same?

  6. A student saves a scanned contract as a low-quality JPEG and says: 'I can always decompress it later to get the exact original scan back.' Correct them.

    Hint: Is JPEG lossless or lossy?

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

Why does zipping a JPEG or MP3 barely make it smaller?

Because those files are already compressed. Compression works by finding repetition and writing it more briefly, and a JPEG has already squeezed most of the repetition out. What is left looks almost random, and random data cannot be shrunk. Zipping a folder of photos may save only 1 or 2 percent, while a folder of plain text files often shrinks to a third of its size or less.

Could a program compress every file to half its size?

No, and the reason is neat. There are 210002^{1000} different files of 1,000 bits, but only about 25012^{501} files of 500 bits or fewer, so most 1,000-bit files cannot get a code half as long. Any lossless method that shrinks some files must leave others the same size or make them bigger. Compression works on real files only because they are full of repeats.

Why do videos get blocky when the internet is slow?

Video apps lower the bit rate to keep the picture moving, so the compression has to throw away more detail. Video compression stores small blocks of the picture and sends mostly what changed between frames. When few bits are available, fast motion like confetti or rain changes too much at once, and the blocks show up as squares.

Learning Path

Data Compression

You are here

Next →

Nothing after this yet
You need Bits and Bytes (how file size is measured) and Data Representation (how text, images and sound become bits) first. Compression adds ways to store the same information in fewer bits, and the choice between lossless and lossy. With it you can estimate download times, pick file formats for a project, and explain why a streamed video turns blocky when the network slows down.

See Also