Base64 Encoding and Decoding: A Complete Guide With Examples
Base64 appears everywhere—email attachments, data URIs, JWT tokens, API authentication. This complete guide explains what it is, why it exists, how to use it in multiple languages, and the pitfalls to avoid.
Reserved ad container for responsive Google AdSense display units
What Is Base64 and Why Does It Exist?
Base64 is a binary-to-text encoding scheme that represents arbitrary binary data using only 64 printable ASCII characters: A–Z, a–z, 0–9, +, and /, with = as a padding character. The name comes from the fact that each Base64 character encodes exactly 6 bits (2⁶ = 64).
Base64 exists because many systems were designed to handle only text—specifically, 7-bit ASCII text. Email protocols (SMTP), early HTTP, and XML all had problems with binary data: null bytes, control characters, and bytes above 127 could corrupt the transmission or be silently dropped. By converting binary data to a safe subset of printable ASCII, Base64 solves this transmission problem.
How Base64 Encoding Works
The algorithm is straightforward:
- Take the binary input and divide it into 3-byte (24-bit) groups
- Split each 24-bit group into four 6-bit chunks
- Map each 6-bit value to a character in the Base64 alphabet
- If the input length isn't divisible by 3, pad with
=characters to make the output length a multiple of 4
The result is always exactly 4/3 the size of the original data, or roughly a 33% size overhead. A 100 KB image becomes a 133 KB Base64 string.
Common Use Cases for Base64
Data URIs (Inline Images in HTML/CSS)
You can embed images directly in HTML or CSS without a separate HTTP request:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." />
This is useful for small icons and critical above-the-fold images where eliminating the extra HTTP round-trip matters. For images larger than ~10 KB, the inline approach increases HTML payload size enough to negate the performance benefit.
JWT (JSON Web Tokens)
A JWT consists of three Base64URL-encoded parts separated by dots: header.payload.signature. Base64URL is a variant of Base64 that replaces + with - and / with _, and omits padding—making it safe to use in URLs and HTTP headers without percent-encoding.
HTTP Basic Authentication
The HTTP Authorization: Basic header encodes credentials as username:password in Base64:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Important: Base64 is encoding, not encryption. Anyone who intercepts the header can trivially decode it. Always use Basic Auth over HTTPS only.
Embedding Binary Data in JSON and XML
JSON and XML are text formats. If you need to include binary data (like a file attachment or cryptographic signature), Base64 encoding converts it to a safe string that won't break the surrounding structure.
Email Attachments (MIME)
Email attachments are encoded in Base64 within MIME multipart messages. This is completely invisible to end users but is why email clients can open attached PDFs and images from any operating system.
Base64 in Code: Examples
JavaScript (Browser)
// Encode
const encoded = btoa("Hello, ZapyNext!");
console.log(encoded); // "SGVsbG8sIFphcHlOZXh0IQ=="
// Decode
const decoded = atob("SGVsbG8sIFphcHlOZXh0IQ==");
console.log(decoded); // "Hello, ZapyNext!"
Note: btoa() and atob() only handle ASCII/Latin-1. For Unicode strings, convert to UTF-8 bytes first using TextEncoder.
Node.js
// Encode
const encoded = Buffer.from("Hello, ZapyNext!").toString("base64");
// Decode
const decoded = Buffer.from(encoded, "base64").toString("utf-8");
Python
import base64
# Encode
encoded = base64.b64encode(b"Hello, ZapyNext!").decode("utf-8")
# Decode
decoded = base64.b64decode(encoded).decode("utf-8")
Command Line (Linux/macOS)
# Encode
echo -n "Hello, ZapyNext!" | base64
# Decode
echo "SGVsbG8sIFphcHlOZXh0IQ==" | base64 --decode
Base64 vs Hex Encoding
Hex (hexadecimal) encoding is another common binary-to-text scheme. It maps each byte to two hex characters (0–9, a–f). Compared to Base64:
- Hex is larger: 2x the original size vs Base64's 1.33x
- Hex is more readable: Easy to inspect individual bytes (each byte is exactly two hex chars)
- Hex is used for: Cryptographic hashes (SHA-256 outputs), MAC addresses, color codes (#FF5733)
- Base64 is used for: Larger binary payloads where compactness matters
When NOT to Use Base64
- Storing passwords: Base64 is not a security measure. Use bcrypt, argon2, or scrypt for password hashing.
- Large file transfers: The 33% overhead is significant for files above a few hundred KB. Use binary protocols or pre-signed URLs instead.
- Treating encoding as encryption: Anyone can decode Base64 in seconds. It is not confidential.
Need to encode or decode Base64 instantly? Try ZapyNext's free Base64 Encoder/Decoder—encode text or files, decode Base64 strings, and toggle Base64URL mode. All processing is done client-side in your browser.
Reserved ad container for responsive Google AdSense display units