Base64 & URL-Safe Base64: How Binary-to-Text Encoding Works
Learn the 64-character radix conversion algorithm, 6-bit chunking, padding rules with equals (=), and URL-safe replacements.
Key takeaways
- Base64 is a binary-to-text encoding format, not an encryption scheme.
- It maps 3 input bytes (24 bits) into 4 printable ASCII characters (6 bits each), introducing an approximate 33% payload size increase.
- Standard Base64 uses + and / characters, which break in URL queries unless converted to URL-Safe Base64 (- and _).
- Padding with equals signs (=) ensures the final encoded string aligns to a multiple of 4 characters.
Companion utility
Try Base64 & URL Encoder / Decoder
Use the browser utility for the same task, then return here for the implementation details.
1. Why Base64 Encoding Was Invented
Early internet communication protocols like SMTP email were built strictly to handle 7-bit ASCII text. Attempting to transmit raw binary images, sound files, or compiled binaries directly across these systems resulted in truncated or corrupted bytes. Base64 (RFC 4648) solved this problem by defining a safe alphabet of 64 printable ASCII characters: uppercase letters A-Z, lowercase letters a-z, digits 0-9, and two symbols (+ and /).
2. The 3-to-4 Character Math Behind the 33% Overhead
Here is the exact conversion math: - Every 3 bytes of raw binary input equal 24 bits. - These 24 bits are split into 4 chunks of 6 bits each. - Each 6-bit chunk represents a number between 0 and 63, which maps directly to a character in the Base64 index table. - Because 3 bytes expand into 4 characters, Base64 encoding always increases data size by roughly 33%. Keep this in mind when inlining large images into HTML or CSS data URIs.
3. Why Standard Base64 Breaks in Web URLs
Standard Base64 includes '+' and '/' characters. In URL query strings, '+' is interpreted as a space character, and '/' is parsed as a path separator. URL-Safe Base64 solves this by replacing '+' with a hyphen (-) and '/' with an underscore (_). In many modern web token implementations (such as JWTs), trailing '=' padding characters are also stripped.
Rana Jawad
Principal Systems Architect at ToolNara. The guides focus on browser runtime behavior, standards, and engineering trade-offs.
View author profile