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:
| Format | First bytes |
|---|---|
| BMP (image) | BM |
| PNG | \x89PNG |
%PDF | |
| ZIP | PK |
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:
| Offset | Size | Content |
|---|---|---|
| 0 | 2 bytes | BM |
| 2 | 4 bytes | file size |
| 18 | 4 bytes | image width |
| 22 | 4 bytes | image 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:
| Code | Meaning |
|---|---|
< | little-endian |
> | big-endian |
i | signed 4-byte integer |
I | unsigned 4-byte integer |
h | signed 2-byte integer |
B | one 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 block | Length | Field |
|---|---|---|
| 0 | 3 | TAG |
| 3 | 30 | title |
| 33 | 30 | artist |
| 63 | 30 | album |
| 93 | 4 | year |
| 97 | 30 | comment |
| 127 | 1 | genre (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_bytesordecode.