Magic Numbers Explained
Magic numbers are constant numerical or text values used to identify a file format or protocol.
What is a Magic Number?
In computer programming, a magic number (or file signature) is a specific sequence of bytes at a fixed location within a file—usually right at the beginning (offset 0). These bytes act as a fingerprint, allowing software to quickly and reliably determine the file's structure without relying on the file extension.
Examples in the Wild
The Windows Executable (MZ)
Every Windows executable (.exe, .dll) begins with the ASCII characters MZ (Hex: 4D 5A). This stands for Mark Zbikowski, one of the original architects of MS-DOS.
The Java Class File
Compiled Java bytecode (.class files) famously starts with the hexadecimal sequence CA FE BA BE ("Cafe Babe").
PDF Documents
PDFs start with the ASCII string %PDF- (Hex: 25 50 44 46 2D), followed by the version number (e.g., 1.4).
Try it yourself
Open any image file in a plain text editor (like Notepad or Vim). You will see gibberish, but look closely at the very first few characters. If it's a PNG, you'll see "PNG" buried in the first line. If it's a GIF, you'll see "GIF89a".
Common Mistakes
| Mistake | Consequence | Better Approach |
|---|---|---|
| Relying on extensions | Malware execution | Use MIME sniffer to check magic number |
| Ignoring offset 0 | False negatives | Verify exact byte offsets |
| Only checking 2 bytes | Format collision | Check full 8-16 byte signature |
FAQ
Are magic numbers always at the start?
No. Some formats like TAR use magic numbers at offset 257. Always check format specifications.
Internal References
Common Mistakes
| Mistake | Consequence | Better Approach |
|---|---|---|
| FileReader.readAsArrayBuffer | Browser Crash (OOM) | Use File.slice for chunks |
| Rendering full DOM | Browser freeze | Virtualized list rendering |
FAQ
What is the max file size?
By using slicing and streams, we can handle files limited only by your OS filesystem (e.g., 2TB on NTFS), not your RAM.