AP Computer Science Principles · Study guide

Data Compression

AP® Computer Science Principles · Big Idea 2 · Data

Data Compression

How compression makes data take fewer bits, why some data shrinks a lot and some hardly at all, and how to choose between lossless and lossy compression.

1What compression does

Data compression reduces the size of data, meaning the number of bits needed to store it or send it. A compression algorithm turns the original data into a smaller encoded version. Later, a decompression algorithm turns that encoded version back into something you can use. Smaller files take less storage space and travel across a network faster.

The question that matters most about any compression method: when you decompress, do you get back the original, bit for bit, or only an approximation of it? That is the difference between lossless and lossy compression.

2Where the savings come from

Compression works by finding redundancy, meaning repetition or predictable patterns, and describing it more briefly. A simple method is run-length encoding: instead of storing every item, store each run of identical items as a count and the item. The text AAAABBBCCDAA becomes 4A3B2C1D2A.

Figure 1. Run-length encoding stores “12 white, 4 black, …” instead of every pixel. With long runs the row shrinks from 40 to 25 bits; with no runs it grows to 200.

The same algorithm shrank one row and made the other five times bigger. How much compression helps depends on both how much redundancy the original data has and which algorithm is used. Real tools use smarter algorithms than run-length encoding, but the rule is the same. The compressor used inside ZIP files and PNG images shrank 980 bytes of repetitive bus-schedule text to 57 bytes (5.8% of the original). Given 980 bytes of random values it produced 991 bytes, slightly bigger than before, because random data has no patterns to describe.

3Lossless compression

Lossless compression algorithms can usually reduce the number of bits while guaranteeing complete reconstruction of the original data. Decoding 4A3B2C1D2A gives back AAAABBBCCDAA with nothing missing. ZIP files and PNG images are lossless.

This shows something that sounds odd at first: fewer bits does not necessarily mean less information. The 25-bit run-length version of the pixel row holds all the information in the 40-bit original; it just says it more efficiently.

Compressing an already-compressed file again barely helps: running the ZIP compressor on its own 57-byte output gave 66 bytes. The first pass already removed the repetition.

4Lossy compression

Lossy compression algorithms can significantly reduce the number of bits, but they only allow reconstruction of an approximation of the original. They throw away detail that people are unlikely to notice, such as tiny changes in shade in a photo or sounds too quiet to hear under louder ones. JPEG photos, MP3 music, and streaming video use lossy compression.

Figure 2. Keeping 4 bits per sample instead of 8 halves the size. The shape survives, but each value is off by up to 7, and the original values cannot be recovered.

Here twelve brightness values that took 8 bits each (96 bits) are stored with 4 bits each (48 bits). The decoded values are close, but 37, 41, 44, and 39 all come back as 40. There is no way to tell from 40 which one it was. Because close values became equal, the data now has runs, and run-length encoding brings it down to 24 bits. This is why lossy compression usually reduces size more than lossless compression: after detail is thrown away, there is more repetition left to compress.

Lost detail is gone for good. Converting a JPEG to PNG does not restore anything; it stores the approximation losslessly from then on.

5Choosing lossless or lossy

Ask two questions. Is quality, or the ability to rebuild the original, what matters most? Then lossless compression is the typical choice. Is keeping the data small, or sending it fast, what matters most, and is a close approximation good enough? Then lossy compression is the typical choice.

SituationChoiceReason
Backing up a team's program codeLosslessOne changed character can stop the program from working; it must come back unchanged.
Archiving X-ray images for later diagnosisLosslessQuality matters most; a discarded detail could be what the doctor needs to see.
Sending a signed contract or a spreadsheetLosslessEvery word and number has to be the same as the original.
Streaming a concert to phonesLossySending fast matters most; a small loss in quality is acceptable.
Thumbnails on a page that must load fastLossySize matters most, and nobody needs every detail of a thumbnail.
A video call on a slow connectionLossyA slightly softer picture beats a frozen one.
The key idea

Compression reduces the number of bits. How much it helps depends on the redundancy in the data and on the algorithm. Lossless compression gives back the original unchanged; lossy compression gives back an approximation but usually makes data smaller. Choose lossless when quality or rebuilding the original matters most, and lossy when size or speed matters most.

6Worked examples

Worked Example 1 Encode and decode

Run-length encoding text

Use run-length encoding on AAAABBBCCDAA, then decode the result. Then try ABCDABCD.

  1. 1
    Group identical neighbors: 4 × A, 3 × B, 2 × C, 1 × D, 2 × A.
  2. 2
    Write count then letter: 4A3B2C1D2A, 10 characters instead of 12.
  3. 3
    Decoding repeats each letter its count: AAAABBBCCDAA, identical to the original.
  4. 4
    ABCDABCD has no repeats, so it becomes 1A1B1C1D1A1B1C1D: 16 characters instead of 8.
Answer: 4A3B2C1D2A. Run-length encoding is lossless, and it only shrinks data that has runs.
Worked Example 2 Choose and justify

Three files

Choose lossless or lossy compression for each, and give the reason: (a) a novelist's only copy of a manuscript; (b) photos for a social media feed that must load on slow phones; (c) a recording of a podcast episode streamed to listeners.

  1. 1
    (a) Every word must survive: rebuilding the original matters most, so lossless.
  2. 2
    (b) Loading fast matters most, and viewers won't miss fine detail, so lossy.
  3. 3
    (c) Sending quickly and using little data matter most, and a small loss in sound quality is acceptable, so lossy.
Answer: (a) lossless, (b) lossy, (c) lossy, each because of what matters most in that situation.
Worked Example 3 Explain a result

Why didn't it shrink?

A student compresses a folder of already-compressed videos and the ZIP file is almost the same size as the folder. Did the compression fail?

  1. 1
    Size reduction depends on the redundancy in the original data.
  2. 2
    Compressed files have had their repetition removed already. In the build of this page, compressing a 57-byte compressed file again gave 66 bytes.
  3. 3
    Nothing went wrong; there was little left to compress.
Answer: No. The videos have almost no redundancy left, so no algorithm can shrink them much more.
Worked Example 4 Reason about information

Fewer bits, same information?

A file shrinks from 40 bits to 25 bits, and decompressing it gives back the identical 40 bits. A classmate says the smaller file “has less information.” Respond.

  1. 1
    The decompressed file is identical, so nothing was lost: the compression is lossless.
  2. 2
    All of the information is still there, written in fewer bits.
Answer: The classmate is wrong. Fewer bits does not necessarily mean less information.
Worked Example 5 Reason about loss

Saving a JPEG as PNG

A photographer saves a photo as a JPEG (lossy), then converts the JPEG to PNG (lossless). Does the PNG have the details the JPEG lost?

  1. 1
    JPEG compression threw some detail away and kept only an approximation.
  2. 2
    PNG stores what it is given without changes, which is the approximation.
Answer: No. Lossless compression preserves what it is given; it cannot restore what lossy compression already removed.

7Common mistakes

Common Mistake 1 · Thinking smaller always means information was lost

Lossless compression makes files smaller and keeps every bit of information. Only lossy compression gives up information.

Common Mistake 2 · Picking by file size first

Ask first whether the original must come back unchanged. If it must, use lossless, even though lossy would be smaller.

Common Mistake 3 · Expecting every file to shrink the same amount

Repetitive data shrinks a lot; random or already-compressed data hardly shrinks at all, and can even grow.

Common Mistake 4 · Believing lossy data can be recovered

Once lossy compression throws detail away, no later step can bring it back.

Justify a compression choice like this

“Lossless compression should be used for the medical scans, because the ability to reconstruct the original images in full is what matters most; lossy compression would discard details a doctor might need.”

Name the method, then tie it to what matters most in the situation: exact reconstruction or quality, or size and transmission time.