Computer Science

Base64 Encoding and Decoding Explained

Understand the mathematics behind 6-bit binary-to-text conversion, padding characters, URL-safe variants, and practical use cases in web systems.

## What Is Base64? **Base64** is a binary-to-text encoding scheme that represents binary data in an ASCII string format. It was designed to ensure that binary data remains intact without modification when transferred across text-based protocols like HTTP headers, MIME email bodies, and XML/JSON documents. --- ## How Base64 Mathematical Encoding Works Base64 works by taking groups of **3 bytes** (24 bits) of raw binary input and splitting them into **4 chunks of 6 bits** each. Since $2^6 = 64$, each 6-bit chunk maps directly to one of 64 printable ASCII characters: - `A - Z` (indices 0–25) - `a - z` (indices 26–51) - `0 - 9` (indices 52–61) - `+` and `/` (indices 62 and 63) ### The 33% Size Overhead Because 3 raw bytes (24 bits) are represented by 4 ASCII characters (32 bits), Base64 encoding introduces an automatic **~33% file size overhead**. --- ## What Does the Equals Sign (`=`) Padding Mean? When your input byte length is not divisible by 3, padding characters (`=`) are appended to the end of the encoded string to ensure the final block contains exactly 4 characters: - If 1 byte remains (8 bits), 2 Base64 characters are generated and padded with two `==`. - If 2 bytes remain (16 bits), 3 Base64 characters are generated and padded with one `=`. --- ## Standard Base64 vs. URL-Safe Base64 Standard Base64 uses `+` and `/`. In web URLs, query parameters, and filenames, these characters can cause conflicts: - `+` is often interpreted as a space in query strings. - `/` acts as a directory path separator. **URL-Safe Base64 (RFC 4648 §5)** replaces `+` with `-` (hyphen) and `/` with `_` (underscore), making the output completely safe for URL paths and tokens. Test your strings and convert files with the [LABSTACK Base64 Encoder & Decoder](/tools/base64-encoder).