<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thiseni Rathnayake on Medium]]></title>
        <description><![CDATA[Stories by Thiseni Rathnayake on Medium]]></description>
        <link>https://medium.com/@thisenirathnayake?source=rss-f0f4f2a728d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*q0W0AzyWmieF_9ev</url>
            <title>Stories by Thiseni Rathnayake on Medium</title>
            <link>https://medium.com/@thisenirathnayake?source=rss-f0f4f2a728d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 23:50:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thisenirathnayake/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[I Built a ZIP Writer to Understand What’s Inside a ZIP File]]></title>
            <link>https://medium.com/@thisenirathnayake/i-built-a-zip-writer-to-understand-whats-inside-a-zip-file-fb851b02fa44?source=rss-f0f4f2a728d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb851b02fa44</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-compression]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Thiseni Rathnayake]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 10:49:48 GMT</pubDate>
            <atom:updated>2026-11-25T10:49:48.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7aCgd9Qa2YKQjHANg0worw.png" /></figure><p><em>It all started with an Instagram reel about Huffman coding.</em></p><p>I came across a video explaining Huffman coding and how it is used in ZIP compression. The idea that you could represent the exact same information using fewer bits caught my attention.</p><p>But then I started wondering about something even more fundamental.</p><p><strong>What actually happens when I turn a bunch of files into a ZIP file?</strong></p><p>I had created and extracted ZIP files countless times. I knew how to use them. I just didn’t know how they worked.</p><p>As a computer science undergraduate, I wanted to explore something outside the usual projects I had been working on. Something that would make me look beneath the abstractions I was used to.</p><p>So instead of calling Python’s zipfile module, I decided to try writing a ZIP file myself.</p><p>Little did I know that before getting anywhere near Huffman coding, I would be questioning my understanding of something as basic as a byte.</p><h3>01. Wait. Where did the number 400 go?</h3><p>I had worked with Python, C++, and Java before. But deliberately constructing a binary file, byte by byte, was unfamiliar territory.</p><p>While exploring Python’s struct module, I encountered something like this:</p><pre>import struct</pre><pre>data = struct.pack(&quot;&lt;I&quot;, 400)<br>print(list(data))</pre><p>The output?</p><pre>[144, 1, 0, 0]</pre><p>I expected to see 400 somewhere.</p><p>Instead, I got four numbers, none of which was 400.</p><p>Why were there four elements? Why was the first one 144? Where had my original number gone?</p><p>The answer was in how integers are represented in bytes.</p><p>A byte contains eight bits, meaning it can represent unsigned values between 0 and 255. The number 400 doesn’t fit into a single byte.</p><p>However:</p><pre>400 = 144 + (1 × 256)</pre><p>In hexadecimal, 400 is 0x00000190.</p><p>Using little-endian byte order, its least significant byte is stored first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHulSXYkDdIBgt1c_qprZw.png" /></figure><pre>Decimal:       400<br>Hexadecimal:   00 00 01 90<br>Stored bytes:  90 01 00 00<br>Byte values:   144  1  0  0</pre><p>The mysterious &quot;&lt;I&quot; suddenly made sense:</p><ul><li>&lt; specifies little-endian byte order.</li><li>I specifies a four-byte unsigned integer.</li></ul><p>It wasn’t changing the number. It was changing how the number was represented.</p><p>Another small realization followed: binary mode doesn’t automatically turn a file into some mysterious, unreadable object. Text files are already stored as bytes. Binary mode simply allows me to work with those bytes directly.</p><p>This was the first time in the project that something I had previously studied became something I could actually see happening.</p><h3>02. Before building ZIP, I invented my own file format</h3><p>Opening the official ZIP specification was slightly intimidating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*266CcBq3lu0GR1ZV" /></figure><p>There were signatures, flags, checksums, offsets, headers, timestamps, and several fields whose purposes I didn’t understand yet.</p><p>So I temporarily abandoned the idea of creating a real ZIP.</p><p>Instead, I asked myself a simpler question:</p><p><strong>What is the minimum information I need to combine two files and separate them again?</strong></p><p>Imagine that I have two text files.</p><pre>hello.txt → Hello<br>notes.txt → My notes</pre><p>Simply joining their contents gives me:</p><pre>HelloMy notes</pre><p>But how would another program know where the first file ends and the second begins? How would it recover their names?</p><p>I needed metadata — information describing the information itself.</p><p>My custom archive format eventually looked like this:</p><pre>[Number of files]</pre><pre>[Filename length]<br>[Content length]<br>[Filename bytes]<br>[Content bytes]</pre><pre>... repeated for each file</pre><p>The writer stored the lengths and contents. The reader used those lengths to determine exactly how many bytes to read next.</p><p>And just like that, I had my own miniature archive format.</p><p>It wasn’t a ZIP file. It didn’t compress anything. Existing archive applications wouldn’t understand it.</p><p>But it worked.</p><p>More importantly, I finally understood that an archive wasn’t necessarily something complicated. At its core, it was an organized sequence of bytes with enough metadata to reconstruct the original files.</p><h3>03. A real ZIP file is essentially a contract</h3><p>My custom format worked because I controlled both the writer and the reader.</p><p>A real ZIP file presented a different challenge.</p><p>I needed to produce something that programs I hadn’t written could understand.</p><p>That meant following the ZIP file format specification published by PKWARE.</p><p>One of the first structures I explored was the local file header.</p><pre>archive.write(struct.pack(&quot;&lt;I&quot;, 0x04034B50))</pre><p>At first, even this hexadecimal value looked unnecessarily complicated.</p><p>But it wasn’t an address or a randomly chosen number.</p><p>It was a signature.</p><p>Every local file header begins with this value, allowing a ZIP reader to identify the type of structure it is reading.</p><p>The signature is followed by fields describing the file, including:</p><ul><li>Compression method</li><li>Modification date and time</li><li>CRC-32 checksum</li><li>Compressed and uncompressed sizes</li><li>Filename length</li></ul><p>Then come the filename and the actual file data.</p><p>Each field has a specified position and size.</p><p>If the specification requires two bytes and I write four, the reader may interpret every subsequent field incorrectly.</p><p>That was something I found particularly interesting about binary formats: the program reading the file doesn’t know my variable names, comments, or intentions.</p><p>It only knows the agreed-upon structure.</p><p>Following that structure correctly is what makes two completely independent programs interoperable.</p><h3>04. Why does ZIP store the same information twice?</h3><p>Once I understood the local file header, I encountered something that confused me even more.</p><p>The central directory.</p><p>It contained filenames, checksums, compressed sizes, uncompressed sizes, and other information I had already written into the local headers.</p><p>Why repeat everything?</p><p>Eventually, I realized that the central directory functions like the index of a book.</p><p>Imagine opening an archive containing hundreds of files.</p><p>Without an index, an application might need to walk through the individual records to discover what the archive contains.</p><p>Instead, ZIP provides a central directory near the end of the archive, containing information about its files and pointers to their local headers.</p><p>The overall structure looks like this:</p><pre>[Local header — File A]<br>[File A data]</pre><pre>[Local header — File B]<br>[File B data]</pre><pre>[Central directory — File A entry]<br>[Central directory — File B entry]</pre><pre>[End of central directory]</pre><p>The end record tells the reader where the central directory begins. Each directory entry tells the reader where the corresponding local header begins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bFAuau54HXUDIT1YlY8O4A.png" /></figure><p>Everything connects.</p><p>This was also when the purpose of another Python function became clear to me:</p><pre>local_offset = archive.tell()</pre><p>archive.tell() returns my current byte position in the file.</p><p>By calling it before writing each local header, I could remember exactly where that header was located.</p><p>I stored the information needed for each central directory entry in a list and returned to it after writing all the file contents.</p><p>A ZIP archive was no longer just a collection of headers in my mind.</p><p>It had an internal navigation system.</p><h3>05. The moment another program understood mine</h3><p>There is something surprisingly satisfying about writing a binary file manually and watching an existing program recognize it.</p><p>After constructing the local headers, central directory, and end record, I tested my archive using:</p><pre>unzip -t output.zip</pre><p>Seeing OK in the terminal felt different from simply getting an expected output from my own program.</p><p>This time, I wasn’t testing my writer against a reader I had created.</p><p>An independent ZIP utility understood the bytes I had written.</p><p>My program was speaking an established file format correctly.</p><p>That was probably one of the most rewarding parts of the project.</p><h3>06. My compression algorithm made a file bigger?</h3><p>Up to this point, I had been focusing on archiving.</p><p>But the entire reason I had started this project was my curiosity about compression.</p><p>I introduced DEFLATE compression using Python’s zlib module.</p><pre>compressor = zlib.compressobj(wbits=-15)</pre><pre>compressed = (<br>    compressor.compress(data)<br>    + compressor.flush()<br>)</pre><p>The -15 was important because ZIP requires raw DEFLATE data for this compression method, rather than DEFLATE data wrapped in a separate zlib header and trailer.</p><p>I ran my first compression experiment.</p><pre>Original size:     27 bytes<br>Compressed size:   29 bytes</pre><p>Wait.</p><p>Wasn’t compression supposed to make things smaller?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5XaZOqg6-O67-MAO" /><figcaption><em>Me trying to figure out how compressing 27 bytes gave me 29 bytes.</em></figcaption></figure><p>It turns out that compression isn’t guaranteed to reduce the size of every input.</p><p>Compressed data has its own encoding overhead. If the original input is very small or lacks exploitable patterns, the savings may not outweigh that overhead.</p><p>So I changed the experiment.</p><p>I filled a text file with repeated lines of:</p><pre>Hello I&#39;m just testing this<br>Hello I&#39;m just testing this<br>Hello I&#39;m just testing this<br>...</pre><p>This time, the results were dramatically different.</p><pre>Original contents:     1,933 bytes<br>Compressed contents:      52 bytes</pre><pre>Reduction: approximately 97%</pre><p>The compressed payload was roughly 37 times smaller than the original.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUNwmrk1CpmsZm-SnYdi7A.png" /></figure><p>These figures refer to the file contents rather than the entire ZIP archive, which also includes headers and directory records.</p><p>Seeing the difference between these two experiments made compression much more intuitive than simply reading its definition.</p><h3>07. How can 52 bytes become 1,933 bytes again?</h3><p>This was the next question I needed to understand.</p><p>If nearly 97% of the bytes were gone, how could the original file possibly be recovered?</p><p>The key is that lossless compression doesn’t discard information. It represents the same information more efficiently.</p><p>Imagine the following text:</p><pre>HELLOHELLOHELLOHELLO</pre><p>Instead of storing every occurrence of HELLO, a compression algorithm could conceptually describe it as:</p><pre>HELLO + repeat this pattern three more times</pre><p>The second representation contains instructions for reconstructing the original.</p><p>DEFLATE achieves compression through a combination of LZ77-style back-references and Huffman coding.</p><p>LZ77 exploits repeated sequences by referring to previously encountered data.</p><p>Huffman coding assigns shorter bit representations to more frequent symbols and longer representations to less frequent ones.</p><p>Together, they can represent certain inputs using considerably fewer bits.</p><p>And the decoder reverses those operations.</p><p>In Python, the DEFLATE decompression operation is:</p><pre>restored = zlib.decompress(compressed, wbits=-15)</pre><p>I could then compare the reconstructed bytes with the original:</p><pre>print(restored == data)</pre><p>The goal wasn’t to recover something approximately similar to the original.</p><p>It was to recover the exact same bytes.</p><p>That’s what makes this lossless compression.</p><h3>08. I built ZIP. I didn’t build DEFLATE.</h3><p>I think this distinction is worth making.</p><p>Although I constructed the ZIP container myself without Python’s zipfile module, I used zlib to handle CRC-32 and DEFLATE compression.</p><p>I didn’t implement LZ77 or Huffman coding from scratch.</p><p>Initially, this felt slightly disappointing.</p><p>After all, a video about Huffman coding was what had inspired the entire project.</p><p>But along the way, I had discovered that I was dealing with two different problems:</p><p><strong>Archiving:</strong> How do I organize multiple files, their contents, and their metadata into a single understandable format?</p><p><strong>Compression:</strong> How do I represent those contents using fewer bits without losing information?</p><p>ZIP provides the container. DEFLATE is one compression method that can be used inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgldzdlIl2XR_U2o5MY0Uw.png" /></figure><p>Separating these concepts helped me appreciate the project for what it actually was rather than what it wasn’t.</p><p>I now have a working ZIP writer that could eventually use a compression algorithm of my own.</p><h3>09. What started as a reel became an entirely different way of learning</h3><p>My biggest takeaway wasn’t learning how to create a ZIP file.</p><p>Python already provides a perfectly good library for that.</p><p>What I enjoyed was discovering the reasoning behind the abstraction.</p><p>Why is a number stored across multiple bytes?</p><p>Why do file signatures exist?</p><p>Why is metadata necessary?</p><p>Why does a ZIP file have an index?</p><p>Why can compression sometimes increase the size of a file?</p><p>Each answer seemed to lead to another question.</p><p>And I found myself learning things I probably wouldn’t have explored if I had simply used an existing library.</p><p>My next step is to implement a standalone Huffman encoder and decoder, followed by LZ77, and eventually explore the details of DEFLATE itself.</p><p>In a way, I’m finally getting back to the algorithm that started all of this.</p><p>The next time I right-click a folder and select <strong>Compress</strong>, I’ll know a little more about what’s happening behind that button.</p><p>And all of this started because I didn’t scroll past an Instagram reel.</p><h3>Project and resources</h3><ul><li><a href="https://github.com/Thiseni-R/zip-from-scratch">GitHub — zip-from-scratch</a></li><li><a href="https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT">PKWARE ZIP File Format Specification</a></li><li><a href="https://docs.python.org/3/library/struct.html">Python struct documentation</a></li><li><a href="https://docs.python.org/3/library/zlib.html">Python zlib documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb851b02fa44" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>