Skip to content

Hex Dump

You'll read a file byte by byte and print it the way xxd does, then write a struct straight to disk and read it back across a byte order problem.

About

A file is a row of bytes and nothing more, and the moment that sinks in, every file format stops being magic. You'll write your own hex dump, compare it against xxd on a PNG and a text file, and then save a struct to disk raw and read it back. Along the way you'll meet the two things that bite everyone: padding the compiler slips between fields, and byte order. Every file you've ever opened went through this.

At a glance

Per requirement
15 XP
Completion bonus
75 XP
Requirements
5
Takes
One evening
Skill level
Beginner (done it a few times)
Cost
Free
Supplies
You need some
Where
At home
Other people
On your own

Requirements

  1. 1
    Write a hex dump that prints 16 bytes per line with offsets and an ASCII column. Open the file in binary mode, read it in chunks with fread, and print each byte as two hex digits. Print a dot for anything that isn't printable in the right-hand column. Run it on a PNG and on its own source file, and compare with xxd on the same file. Take a screenshot of your dump next to xxd's. Photo
  2. 2
    Find the magic bytes at the start of three different file types and name them. A PNG starts with 89 50 4E 47, a ZIP starts with 50 4B, and a PDF starts with 25 50 44 46. Dump the first line of each with your tool and look them up. Then rename a PNG to .txt and show the bytes don't care what the name says. Take a screenshot of the three first lines. Photo
  3. 3
    Write a struct to a file with fwrite and read it back with fread into a fresh struct. Use a struct with a char, an int, a double and an eight-byte char array. Write it, read it into a second variable, and print both. Then dump the file and find where each field sits, including the padding bytes the compiler put between the char and the int. Take a screenshot of the dump with the fields marked. Photo
  4. 4
    Write the number 258 to a file in little-endian and big-endian order and show the bytes. 258 is 01 02 in big-endian and 02 01 in little-endian, so it's the easiest number to tell apart. Write both by hand with shifts and masks rather than trusting the struct. Then read a four-byte big-endian number from a real format (a PNG chunk length works) and print it correctly on your machine. Take a screenshot of both dumps and the decoded number. Photo
  5. 5
    Copy a 100 MB file with the read and write system calls and time it with three buffer sizes. Make a test file with dd or by writing random bytes. Copy it with a 1 byte buffer, a 4 KB buffer and a 1 MB buffer, using read and write rather than fread so every call goes to the kernel, and time each. The 1 byte version makes 200 million system calls and takes minutes, and that gap is the cost of a system call. Check the copy with sha256sum. Take a screenshot of the three timings and the matching checksums. Photo