DEV Community

Cover image for How Does File Compression Work?
Hossein Naseri
Hossein Naseri

Posted on

How Does File Compression Work?

How Does File Compression Work?

Compression is a way to reduce a file's size.

To understand it, imagine you're asked to count the cars in a parking lot.

You could report:

a BMW

a BENZ

a BENZ

a BMW

a FORD

a BMW

a FORD

Or, if you wanted to send the shortest report possible, you could simply say:

3 BMW

2 BENZ

2 FORD

It's the same information, but it takes less space.

That's the basic idea behind many compression techniques: find repeating patterns and store them more efficiently.

Every file on your phone or computer is ultimately stored as a long sequence of tiny ON and OFF states, usually represented as 0s and 1s.
For example:

000000111111111010100000100000010010000001010111111111
Enter fullscreen mode Exit fullscreen mode

Instead of storing every digit individually, the computer can look for repeated patterns.

For example:

00000
Enter fullscreen mode Exit fullscreen mode

becomes

5 zeros
Enter fullscreen mode Exit fullscreen mode

and

11111
Enter fullscreen mode Exit fullscreen mode

becomes

5 ones
Enter fullscreen mode Exit fullscreen mode

So our data could be represented like this:

(6 zeros)(8 ones)0101(5 zeros)1(6 zeros)1001(6 zeros)1010(8 ones)
Enter fullscreen mode Exit fullscreen mode

Or, if we represented those 0s and 1s visually, it might look something like this:

Rather than storing every individual digit, the computer stores a shorter description of repeating patterns.

This is one of the simplest forms of compression.

The goal is simple:

Store the same information using less space.

Smaller files take up less storage, travel across the internet faster, and use less bandwidth.

Real compression algorithms are much smarter than this example, but they all follow the same basic idea:

Don't store repetition. Store a shorter description of it instead.

Top comments (0)