Binary Files · 3 / 14 Theory

File formats: headers, offsets and struct

A binary file is not a pile of random bytes: it follows a format that says what each byte means according to its position. Reading a format is about knowing where to look.

Magic numbers

Almost all formats start with a few fixed bytes that identify the file type:

FormatFirst bytes
BMP (image)BM
PNG\x89PNG
PDF%PDF
ZIPPK
with open("image.bmp", "rb") as f:
    header = f.read(2)

if header == b"BM":
    print("It is a BMP")
else:
    print("Not a valid BMP file")

A typical mistake: comparing with "BM" instead of b"BM". A bytes is never equal to a str.

Offsets: where each piece of data is

The format specification says at which position (offset) each field is. For example, in a BMP header:

OffsetSizeContent
02 bytesBM
24 bytesfile size
184 bytesimage width
224 bytesimage height

To read a field you slice the bytes by its positions: header[18:22] are the 4 bytes of the width.

From bytes to number

Multi-byte numbers are stored in a specific order. BMP uses little-endian: the least significant byte goes first. For example, 48 (0x30) in 4 bytes is stored as 30 00 00 00:

data = b"\x30\x00\x00\x00"
print(int.from_bytes(data, "little"))   # 48
print(int.from_bytes(data, "big"))      # 805306368  (wrong order)

The struct module

struct.unpack converts several fields at once according to a format. Common letters:

CodeMeaning
<little-endian
>big-endian
isigned 4-byte integer
Iunsigned 4-byte integer
hsigned 2-byte integer
Bone byte (0–255)
import struct

with open("image.bmp", "rb") as f:
    header = f.read(54)

width, height = struct.unpack("<ii", header[18:26])   # two 4-byte integers
print(f"{width}x{height}")

It is the scheme of Read dimensions of BMP image. unpack always returns a tuple, even with a single value, and the number of bytes you pass must match the format ("<ii" is 8 bytes).

Reading from the end: ID3 tags

Some formats store data at the end of the file. An MP3 with an ID3 v1 tag ends with a block of exactly 128 bytes that starts with TAG:

Position inside the blockLengthField
03TAG
330title
3330artist
6330album
934year
9730comment
1271genre (a number)
with open("song.mp3", "rb") as f:
    data = f.read()

block = data[-128:]                  # the last 128 bytes
if len(data) >= 128 and block[0:3] == b"TAG":
    title = block[3:33].decode("latin-1").strip("\x00 ")
    genre = block[127]               # an integer, when indexing a bytes
    print(title, genre)
else:
    print("No tag")

The texts are padded with spaces or \x00 bytes up to their length; strip("\x00 ") removes that padding. It is the key of Read ID3 v1 tags from MP3 file.

Working method

  • Find the format specification (the table of offsets).
  • Read the part you need with read(n) or with a slice.
  • Check the magic number before interpreting anything.
  • Convert with struct, int.from_bytes or decode.