KS48525 3.3.7 30 min read 10 question quiz 18 exam marks

Data Compression, Huffman and RLE

Why compression matters, the difference between lossy and lossless, and full worked methods for both Huffman coding and run length encoding, including how to calculate the saving.

Why compress at all

Compression means reducing the number of bits needed to store a file.

Three reasons it matters, and questions expect the reason rather than just the word:

  • Storage. More files fit in the same space.
  • Transmission time. A smaller file takes less time to send, which matters most on a slow connection.
  • Bandwidth. Less data sent means lower cost and less congestion, which is why streaming services compress heavily.

Lossy and lossless

Lossy compression permanently removes data judged to be less important. The file gets much smaller and the original cannot be recovered exactly. JPEG images and MP3 audio are lossy: MP3 removes frequencies most people cannot hear, and JPEG discards fine colour detail the eye is poor at noticing.

Lossless compression stores the same information more efficiently, so the original file is reconstructed exactly. PNG images and ZIP archives are lossless.

LossyLossless
Original recoverableNoYes
Size reductionLargeMore modest
Suitable forPhotographs, music, videoText, program code, spreadsheets, archives
Never use lossy compression on text or code

Removing "less important" characters from a program is not a smaller program, it is a broken one. That is exactly the reasoning a question about choosing a method wants.

Lossless and lossy compression compared with the original fileCompression, with the length of each bar at the bottom standing for the size of the file. The original holds every byte of the data. Lossless compression finds repetition and records it more briefly: run length encoding replaces a run of identical values with the value and a count, so six As followed by three Bs becomes 6A 3B, and Huffman coding gives the most common symbols the shortest codes. Nothing is discarded, so unpacking returns exactly the original file, bit for bit, though the saving is modest. Lossy compression throws data away permanently, such as detail the eye is unlikely to miss, and so the file becomes much smaller but the original can never be recovered. Text and program code must be lossless because one wrong byte breaks them. Photos and music can usually be lossy.OriginalLosslessLossy12 MBevery byte of the data,nothing thrown awayfinds repetition and says it shorterAAAAAABBB6A3B6 MBunpack it: identical1 MBdetail thrown awayand never coming backOriginal12 MBLossless6 MBLossy1 MB1234
  1. The original file: every byte of the data, nothing thrown away.
  2. Lossless finds repetition and records it more briefly.
  3. Unpack it and you get back exactly what you started with.
  4. Lossy throws data away permanently, and gets much smaller.
Ask what happens if one byte changes. If the answer is that it breaks, the compression has to be lossless.
Lossless against lossy compression: a picture before and after, and when to use eachTwo ways to compress a file. With lossless compression a 5 megabyte picture is compressed to 3.2 megabytes using something like ZIP, PNG or FLAC, and when it is restored it is identical to the original, because nothing is lost. With lossy compression the same picture is compressed to 0.5 megabytes using something like JPEG, MP3 or MP4, and when it is restored it is not identical, because detail has been thrown away for good. Lossless suits text, programs, spreadsheets and medical scans, anything that must be exact. Lossy suits photos, music and video, where small losses go unnoticed and the files shrink a lot.Lossless1original5.0 MBcompressed3.2 MBrestoredidenticalZIP, PNG, FLACnothing is lost: every bit comesbackLossy2original5.0 MBcompressed0.5 MBrestorednot identicalJPEG, MP3, MP4detail is thrown away for goodWhich to use?3Losslesstext, programs, spreadsheets, medicalscans: anything that must be exactLossyphotos, music, video: small losses gounnoticed and the files shrink a lot
  1. Lossless: the file gets smaller, and decompressing gives back exactly the original.
  2. Lossy: the file gets much smaller, but detail is thrown away for good, so it cannot be restored exactly.
  3. Choose lossless when the data must be exact, and lossy when small losses do not matter.
Lossy files can never be restored to the original. That is the trade for a much smaller file.

Run length encoding

Run length encoding, or RLE, replaces a run of repeated values with a single value and a count of how many times it occurs.

Take a row of pixels: W W W W W B B W W W W W W B B B

That is 16 values. Written as run length pairs it becomes:

5W 2B 6W 3B

Four pairs, eight values in total, storing exactly the same information. Nothing has been lost, so RLE is lossless.

Working out the saving

Count what each version costs in the same unit. If each character costs one byte and each count costs one byte:

  • Original: 16 bytes.
  • Compressed: 4 pairs of 2 bytes, which is 8 bytes.
  • Saving: 8 bytes, which is 50 per cent.
RLE can make a file bigger

Apply it to A B A B A B A B and every run has length one, so eight values become eight pairs and sixteen values. RLE only helps when the data contains long runs, which is why it suits simple graphics with blocks of flat colour and is useless on photographs.

Run length encoding a small black and white image, and when it does not helpRun length encoding, RLE, stores a run of identical values once, with a count, instead of storing every value. A small black and white image, twelve pixels wide and six tall, is stored row by row. The first and last rows are all white, so each is just 12W. The middle rows are runs of white, then black, then white: 5W 2B 5W, then 4W 4B 4W, then 3W 6B 3W, then 2W 8B 2W. The 72 pixels become 14 runs, so there is much less to store. RLE is lossless, because the original can be rebuilt exactly. It only helps when values repeat. A row that alternates white, black, white, black becomes eight runs of 1, one for every pixel, so nothing is saved and the file can grow.Run length encoding: store a run once, with its length12W›5W2B5W›4W4B4W›3W6B3W›2W8B2W›12W›the image: 12 × 6 = 72 pixelseach row as runs72 pixels14 runsmuch less to storeIt fails when nothing repeats8 pixels1W1B1W1B1W1B1W1B8 runs: no saving, and it can even grow123
  1. Count runs of the same colour along each row, and write the count then the colour.
  2. 72 pixels become 14 runs. The saving is big because long runs repeat.
  3. If the values keep changing, every run is 1 long and RLE saves nothing, and may be larger.
RLE is lossless and works best on images with large blocks of one colour, such as logos, icons and diagrams.

Huffman coding

Huffman coding gives the most frequent characters the shortest binary codes and the least frequent the longest, so the total number of bits needed falls.

Building the tree

Take the string BANANA. The frequencies are A three times, N twice and B once.

  1. Write each character as a node with its frequency.
  2. Repeatedly take the two lowest frequencies and join them under a new node whose frequency is their total.
  3. Carry on until one node remains, which is the root.
  4. Label every left branch 0 and every right branch 1.
  5. A character's code is the sequence of labels from the root down to it.

For BANANA that gives A as 0, N as 10 and B as 11, or a mirror image of that depending on which side you place each pair. Either is acceptable as long as it is consistent and you read it off your own tree.

Reading a code off the tree

Start at the root and follow the bits. When you reach a leaf, that is your character, and you go back to the root for the next one. Because no character's code is the start of another character's code, the stream can be decoded without any separators.

Calculating the saving

BANANA in ASCII: 6 characters at 7 bits each is 42 bits.

With the codes above:

B  11        2 bits
A  0         1 bit  x 3  = 3 bits
N  10        2 bits x 2  = 4 bits
total                     = 9 bits

The saving is 42 minus 9, which is 33 bits.

The three things a Huffman question asks

Build the tree, give a character's code by reading down from the root, and calculate the number of bits needed compared with ASCII. Practise all three, because a single question usually asks for all three.

Huffman coding of the message AAAAABBBCCD: count, build the tree, read the codesHuffman coding compresses text by giving common characters short codes. The message AAAAABBBCCD has 11 characters, which would take 88 bits in ASCII. Count them first: A appears 5 times, B 3 times, C twice and D once. Build the tree by repeatedly joining the two smallest counts. D 1 and C 2 join to make a node worth 3. That node and B, 3, are now the two smallest, and join to make 6. Then 6 and A, 5, join to make the root, 11. Label every left branch 0 and every right branch 1, and read the code for each letter from the root down. A is 0, B is 10, D is 110 and C is 111. The most common letter has the shortest code. The message now needs 5 times 1, plus 3 times 2, plus 2 times 3, plus 1 times 3, which is 20 bits, about 77 percent smaller than 88. Huffman coding is lossless.messageAAAAABBBCCD11 charactersin ASCII: 88 bits1 CountA5B3C2D1least common is joined first2 Build the tree0101011163A:5B:3D:1C:23 CodesA0B10D110C111common lettersget short codesASCII11 × 8 = 88 bitsHuffman20 bits5×1 + 3×2 + 2×3 + 1×3 = 20, about 77% smaller123
  1. Count how often each character appears.
  2. Join the two smallest counts into a new node, and repeat until one node, the root, is left. Label branches 0 and 1.
  3. Read each code from the root down to its letter. Frequent letters get the shortest codes.
Common characters get short codes and rare ones get long codes, so the total is smaller. No code is the start of another.

Key terms you must be able to define

Compression
Reducing the number of bits needed to store a file.
Lossy compression
Compression that permanently removes data, so the original cannot be recovered exactly.
Lossless compression
Compression that stores the same information more efficiently, so the original can be reconstructed exactly.
Run length encoding
A lossless method that replaces a run of repeated values with the value and a count.
Huffman coding
A lossless method that gives frequent characters shorter binary codes and rare characters longer ones.
Huffman tree
A binary tree built from character frequencies, from which each character's code is read off.
Bandwidth
The amount of data that can be transmitted in a given time.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineCompression
AnswerReducing the number of bits needed to store a file.
DefineLossy compression
AnswerCompression that permanently removes data, so the original cannot be recovered exactly.
DefineLossless compression
AnswerCompression that stores the same information more efficiently, so the original can be reconstructed exactly.
DefineRun length encoding
AnswerA lossless method that replaces a run of repeated values with the value and a count.
DefineHuffman coding
AnswerA lossless method that gives frequent characters shorter binary codes and rare characters longer ones.
DefineHuffman tree
AnswerA binary tree built from character frequencies, from which each character's code is read off.
DefineBandwidth
AnswerThe amount of data that can be transmitted in a given time.

Reach the top grade on this topic

Huffman and RLE are the two places on this specification where careful working is worth several marks at once.

Build the tree by always combining the two lowest frequencies. Write the running totals as you go, so the examiner can follow your method even if one branch ends up on the wrong side.

Say why your codes have no separators. A top answer notes that no code is a prefix of another, which is what makes the stream decodable, and that is a mark most candidates never earn.

Compare against the right baseline. A saving question means comparing your total against the same string in ASCII, so state the ASCII cost, state the Huffman cost, and subtract.

Justify lossy or lossless from the file type. Photographs and music tolerate lossy compression because human perception does not notice the loss. Text and code cannot, because every character carries meaning.

Mistakes that cost marks here

Avoid these
  • Saying lossless compression removes data. It removes redundancy in how data is stored, not the data itself.
  • Combining the two highest frequencies when building a Huffman tree instead of the two lowest.
  • Forgetting that a Huffman code is read from the root downwards, not from the leaf upwards.
  • Assuming RLE always reduces the size. On data with no runs it makes the file larger.
  • Comparing a Huffman total against 8 bits per character when the question specified 7 bit ASCII, or the reverse.
Fun fact

Huffman coding was invented in 1951 by David Huffman, a student who took it on rather than sit a final exam. His method turned out to be provably optimal, which his own professor had failed to find.

Knowledge check

0 of 10 answered
1What is the defining feature of lossy compression?
2Why must a text document be compressed losslessly?
3How would W W W B B B B W be written using run length encoding?
4When does run length encoding make a file larger?
5In Huffman coding, which characters get the shortest codes?
6When building a Huffman tree, which two nodes are combined at each step?
7The word MISSISSIPPI is 11 characters. In 7 bit ASCII, how many bits does it take?
8Why can a Huffman coded stream be decoded without separators between characters?
9Which pair of file types are most appropriately compressed lossily?
10A file compresses from 2000 bits to 750 bits. What is the percentage saving?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

18 marks
1State two reasons why a file might be compressed before being sent over the internet.2 marks
State

Mark scheme0 / 2
  • LIt takes less time to transmit
  • LIt uses less bandwidth, or takes less storage space at the other end
Model answer

A compressed file contains fewer bits, so it takes less time to send, which matters particularly on a slow connection. It also uses less bandwidth, which reduces congestion on the network and lowers the cost for anybody paying for the data they use.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Explain the difference between lossy and lossless compression, and give one appropriate use of each.4 marks
Explain

Mark scheme0 / 4
  • LLossy compression permanently removes data, so the original cannot be recovered
  • LGives a suitable lossy use such as photographs, music or video
  • LLossless compression stores the same data more efficiently, so the original is recovered exactly
  • LGives a suitable lossless use such as text, program code or a spreadsheet
Model answer

Lossy compression achieves a large reduction by permanently discarding data judged to be less important, which means the original file cannot be reconstructed exactly. It is appropriate for photographs and music, where human perception does not register the detail that is removed, which is why JPEG and MP3 are used. Lossless compression instead finds a more efficient way of storing exactly the same information, so the original is recovered perfectly, at the cost of a more modest reduction in size. It is essential for text documents, program code and spreadsheets, where every character carries meaning and discarding any of it would corrupt the file.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3A row of an image contains the pixels W W W W B B W W W W W W. Show how this row would be stored using run length encoding, and state one reason why RLE would be a poor choice for a photograph.4 marks
Show

Mark scheme0 / 4
  • LIdentifies the runs correctly as four W, two B, six W
  • LWrites them as value and count pairs
  • LA photograph has very few long runs of identical pixels
  • LSo RLE would give little saving and could make the file larger
Model answer

The row contains four W, then two B, then six W, so under run length encoding it is stored as the pairs 4W, 2B, 6W. That is three pairs, six values in total, in place of the original twelve, and nothing has been lost. Run length encoding would be a poor choice for a photograph because photographs contain gradients and noise rather than blocks of identical colour, so almost every run has a length of one. Each single pixel would then be stored as a value and a count, which is two values where one was needed, and the compressed file would be larger than the original.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4The word ABRACADABRA is to be compressed using Huffman coding. Describe how the Huffman tree would be constructed, and explain how the code for a character is obtained from it.5 marks
Describe

Mark scheme0 / 5
  • LCounts the frequency of each character
  • LCreates a node for each character with its frequency
  • LRepeatedly combines the two nodes with the lowest frequencies under a new parent
  • LContinues until one root node remains, and labels branches 0 and 1
  • LA character's code is read by following the branch labels from the root down to that character
Model answer

First count how often each character occurs: A appears five times, B twice, R twice, C once and D once. Each character becomes a node carrying its frequency. The two nodes with the lowest frequencies, C and D, are then joined under a new parent node whose frequency is their total of two. That process repeats, always taking the two lowest frequencies still available, until a single root node remains holding the total of eleven. Every left branch is then labelled 0 and every right branch 1. To obtain the code for a character you start at the root and follow the branches down to that character's leaf, writing down each label as you pass it. Because A is the most frequent it ends up nearest the root and gets the shortest code, while C and D are deepest and get the longest, which is what makes the total number of bits smaller than fixed length coding would need.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5A message of 40 characters is stored in 7 bit ASCII. After Huffman coding it needs 148 bits. Calculate the number of bits saved and the saving as a percentage of the original.3 marks
Calculate

Mark scheme0 / 3
  • LCalculates the ASCII size as 280 bits
  • LCalculates the saving as 132 bits
  • LGives approximately 47 per cent
Model answer

In 7 bit ASCII the message takes 40 multiplied by 7, which is 280 bits. Huffman coding needs 148 bits, so the saving is 280 minus 148, which is 132 bits. As a percentage of the original that is 132 divided by 280, which is 0.4714, or approximately 47 per cent.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 18