Developer Guide

File Magic Numbers in Hex: JPEG, PNG, PDF, ZIP and More

File “magic numbers” are fixed byte prefixes that identify a format. Documentation almost always prints them as hex because two digits per byte stay short and copy-paste friendly. Learning a small set of signatures is one of the fastest ways to debug corrupt downloads, mislabeled uploads, and “this isn’t a PNG” support tickets.

Decode unknown prefixes with Hex to String or inspect bits with Hex to Binary.

Why magic numbers show up as hex

Raw bytes are awkward in prose. Hex keeps tables readable and aligns with hex editors. Example: PNG begins with eight bytes commonly written as:

89 50 4E 47 0D 0A 1A 0A

50 4E 47 is ASCII PNG. The leading 89 is intentionally non-text so naive tools do not treat the file as plain text.

Signatures worth knowing

FormatHex prefixNotes
JPEGFF D8 FFEnds with FF D9
PNG89 50 4E 47 0D 0A 1A 0AIncludes ASCII PNG
GIF47 49 46 38ASCII GIF8
PDF25 50 44 46ASCII %PDF
ZIP50 4B 03 04ASCII PK (also jars, docx, apk containers)
ELF7F 45 4C 46Many Linux executables
UTF-8 BOMEF BB BFHint for text, not a file type

A reliable check procedure

  1. Read the first 8–16 bytes (more for formats with longer headers).
  2. Print them as spaced hex.
  3. Compare against a short signature table.
  4. If bytes look printable, also interpret as ASCII/UTF-8 for a second opinion.
  5. Remember: a matching prefix does not prove the whole file is intact.
from pathlib import Path

def head_hex(path: str, n: int = 16) -> str:
    b = Path(path).read_bytes()[:n]
    return b.hex(" ")

print(head_hex("sample.bin"))
<?php
$fh = fopen('sample.bin', 'rb');
$head = fread($fh, 16);
fclose($fh);
echo bin2hex($head);

Real-world failure modes

Magic vs content-type vs extension

Browsers and CDNs may trust Content-Type or the file extension. Those lie often. Magic bytes are closer to the truth, but still only a prefix check. Security-sensitive uploaders should combine:

FAQ

Is every file type identifiable this way?
No. Plain UTF-8 text has no required magic. CSV/JSON are conventions.

Should I store magic tables in my app?
For a few formats, yes. For broad detection, use a maintained library rather than hand-rolling hundreds of rules.

Related: hex encoding overview · Hex vs Base64 · colors as hex bytes: Hex to RGB.