Base64 Encoding Guide: Strings, Images & Code Examples
Base64 Encoding Guide: What It Is and How It Works
This comprehensive base64 encoding guide explains the Base64 algorithm from first principles โ how binary data maps to printable ASCII characters, how to encode and decode text in JavaScript, Python, Go, and Bash, and when to use standard Base64 vs Base64URL. If you need to encode a string right now, use the free **Base64 Encoder/Decoder tool โ it runs entirely in your browser with zero server uploads. To compare Base64 against raw hexadecimal representations, review our Base64 vs Hex Encoding Comparison**.
Base64 is a standardized binary-to-text encoding algorithm (defined in RFC 4648) designed to translate raw binary sequences into an ASCII string representation using a 64-character alphabet. Because legacy internet protocols (such as SMTP for email attachments, JSON REST APIs, and HTTP headers) were designed primarily for 7-bit or 8-bit text transmission, raw binary bytes can easily be corrupted or stripped by intermediate gateways. Base64 ensures safe, lossless transmission of binary assets across text-only channels.
The core mathematical principle relies on grouping binary data into 24-bit blocks (3 raw bytes of 8 bits each), which are then divided into four 6-bit chunks. Each 6-bit chunk has a numerical value from 0 to 63 (2^6 = 64), which directly indexes a character in the standardized Base64 alphabet:
- Indices 0โ25: Uppercase letters
AโZ - Indices 26โ51: Lowercase letters
aโz - Indices 52โ61: Digits
0โ9 - Index 62: Plus sign
+ - Index 63: Forward slash
/ - Padding character: Equals sign
=
Step-by-Step 24-Bit Bitwise Translation Example
Consider the 3-letter ASCII word "Man":
1. ASCII Characters: M (ASCII decimal 77), a (ASCII decimal 97), n (ASCII decimal 110)
2. 8-Bit Binary Streams: 01001101 01100001 01101110 (Total = 24 bits)
3. Re-grouped into four 6-bit integers:
- 010011 = Decimal 19 โ Base64 index T
- 010110 = Decimal 22 โ Base64 index W
- 000101 = Decimal 5 โ Base64 index F
- 101110 = Decimal 46 โ Base64 index u
4. Final Base64 Output: TWFu
ASCII Input: M (77) a (97) n (110)
8-bit Octets: 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 1 1 0 1 1 1 0
โโโโโโโฌโโโโโโ โโโโโโโฌโโโโโโ โโโโโโโฌโโโโโโ
24-bit Stream: 0 1 0 0 1 1 0 1 0 1 1 0 0 0 0 1 0 1 1 0 1 1 1 0
โโโโโฌโโโโ โโโโโฌโโโโ โโโโโฌโโโโ โโโโโฌโโโโ
6-bit Chunks: 010011 010110 000101 101110
Decimal Values: 19 22 5 46
Base64 Output: T W F uBase64 Radix Index Table (Values 0 to 63)
The table below outlines the complete RFC 4648 radix-64 alphabet mapping:
- 0โ9:
A(0),B(1),C(2),D(3),E(4),F(5),G(6),H(7),I(8),J(9) - 10โ19:
K(10),L(11),M(12),N(13),O(14),P(15),Q(16),R(17),S(18),T(19) - 20โ29:
U(20),V(21),W(22),X(23),Y(24),Z(25),a(26),b(27),c(28),d(29) - 30โ39:
e(30),f(31),g(32),h(33),i(34),j(35),k(36),l(37),m(38),n(39) - 40โ49:
o(40),p(41),q(42),r(43),s(44),t(45),u(46),v(47),w(48),x(49) - 50โ59:
y(50),z(51),0(52),1(53),2(54),3(55),4(56),5(57),6(58),7(59) - 60โ63:
8(60),9(61),+(62),/(63) - Padding Marker:
=(indicates zero-padded remaining octets)
To inspect character codes in decimal or hexadecimal format, test inputs with our **Text to ASCII Converter**.
Base64 Padding Rules Explained (= and ==)
Since Base64 processes data in 3-byte (24-bit) chunks, input byte lengths that are not multiples of 3 require zero-bit padding and special = suffix markers to indicate the missing source bytes:
Case 1: Input Length is Divisible by 3 (Remainder 0)
No padding is required. 3 input bytes become exactly 4 Base64 characters.
- Example: "any" (3 bytes) โ "YW55" (4 chars, no =)
Case 2: 2 Bytes Remaining (Remainder 2)
The 2 bytes (16 bits) are split into two full 6-bit chunks (12 bits) and a third chunk of 4 bits padded with two zero bits (00). The fourth position is replaced with a single = padding character.
- Example: "an" (2 bytes = 16 bits) โ "YW4=" (4 chars ending in single =)
Case 3: 1 Byte Remaining (Remainder 1)
The 1 byte (8 bits) is split into one 6-bit chunk and a second chunk of 2 bits padded with four zero bits (0000). The third and fourth positions are filled with two == padding characters.
- Example: "a" (1 byte = 8 bits) โ "YQ==" (4 chars ending in double ==)
Why Base64 Increases File Size by ~33%
Because 3 bytes (24 bits) are converted into 4 characters (32 bits), Base64 encoding introduces a mathematical 33.3% size overhead (4 / 3 = 1.3333). In contrast, hexadecimal encoding (4 bits per character) requires 2 characters per byte, resulting in a 100% overhead. To inspect size metrics side-by-side, visit our **Base64 vs Hex Encoding Comparison**.
Mathematical Output Formula
The exact formula to compute the resulting Base64 length (including padding) is:
Math.ceil(inputBytes / 3) * 4
For example, a raw 1,000-byte string or binary file yields:
Math.ceil(1000 / 3) * 4 = 334 * 4 = 1,336 Base64 characters (~33.6% increase).
When Base64 Encoding is Recommended:
- Small Icon & SVG Inlining: Embedding small logos or favicons (< 5KB) directly in CSS/HTML to eliminate round-trip HTTP requests
- Data URIs: Displaying dynamically generated Canvas graphics, QR codes, or PDF previews in browser memory
- HTTP Basic Authentication: Passing credentials in Authorization: Basic <base64> headers
- Cryptographic Hashes & Keys: Storing SHA-256 digests, RSA public keys, and HMAC signatures in JSON or YAML configuration files
When to Avoid Base64:
- Large Media Files (> 50KB): Embedding large hero banners or audio clips wastes client bandwidth and increases JavaScript JSON parse overhead
- Database Column Storage: Always store binary files in native BLOB or BYTEA columns rather than Base64 strings to save 33% disk storage and memory cache
Standard Base64 vs Base64URL (RFC 4648 ยง5)
Standard Base64 contains characters that conflict with standard URL query strings and URI path syntax:
- + (Plus): Interpreted as a space in standard URL query parameters (?query=a+b)
- / (Slash): Acts as a directory path separator in RESTful URL routing (/users/123)
- = (Equals): Acts as a key-value assignment operator in query parameters (?key=val)
To safely transmit Base64 in URL paths, query parameters, filenames, and JSON Web Tokens (JWT), RFC 4648 Section 5 defines Base64URL:
- Replace + with - (Minus / Dash)
- Replace / with _ (Underscore)
- Omit trailing = padding (implicit length reconstruction)
Standard Base64: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9+SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV/adQssw5c=
Base64URL Format: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9-SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5cYou can test URI component escaping with our **URL Encoder/Decoder, inspect raw Base64URL signatures in the JWT Decoder, or explore token structures in our comprehensive Understanding JWT Tokens Guide**.
Practical Guide to HTML Data URIs for Images and Fonts
A Data URI allows inline embedding of media directly inside HTML attributes or CSS rules without external network fetches:
<!-- Inlining a PNG Image in HTML -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" alt="Sample Pixel" />/* Inlining a Custom SVG Background in CSS */
.badge-icon {
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCI+PHBhdGggZD0iTTUgMTNsNCA0TDE5IDciIHN0cm9rZT0iIzEwYjk4MSIgZmlsbD0ibm9uZSIvPjwvc3ZnPg==");
}Use the **Base64 Image Converter** to drag-and-drop PNG, JPG, SVG, and WebP files to generate instant Data URIs with 1-click clipboard copying.
Multi-Language Base64 Code Implementations
1. Modern JavaScript & TypeScript (Browser & Node.js)
In modern web browsers, use TextEncoder and TextDecoder to handle Unicode and UTF-8 characters without encountering btoa() character range exceptions. In ECMAScript 2024+, you can also use native Uint8Array.prototype.toBase64():
// Modern ECMAScript (2024+ Standard)
const bytes = new TextEncoder().encode("Telekit Tools ๐");
// @ts-ignore
const modernB64 = bytes.toBase64?.() ?? window.btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join(""));
// UTF-8 Safe Browser Base64 Encoding
function encodeBase64(text: string): string {
const bytes = new TextEncoder().encode(text);
const binaryString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join("");
return window.btoa(binaryString);
}
// UTF-8 Safe Browser Base64 Decoding
function decodeBase64(base64: string): string {
const binaryString = window.atob(base64);
const bytes = Uint8Array.from(binaryString, (char) => char.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
// Node.js Native Buffer Implementation
const nodeEncoded = Buffer.from("Telekit Tools ๐", "utf-8").toString("base64");
const nodeDecoded = Buffer.from(nodeEncoded, "base64").toString("utf-8");
// Node.js Base64URL
const base64Url = Buffer.from("hello world", "utf-8").toString("base64url");2. Python (Standard Library base64)
import base64
# Standard Base64 Encoding
text = "Telekit Tools ๐"
raw_bytes = text.encode("utf-8")
encoded_b64 = base64.b64encode(raw_bytes).decode("ascii")
print(f"Base64: {encoded_b64}")
# Base64 Decoding
decoded_bytes = base64.b64decode(encoded_b64)
decoded_text = decoded_bytes.decode("utf-8")
print(f"Decoded: {decoded_text}")
# URL-Safe Base64 (Base64URL)
url_safe_b64 = base64.urlsafe_b64encode(raw_bytes).decode("ascii").rstrip("=")
print(f"Base64URL: {url_safe_b64}")3. Go (Golang encoding/base64)
package main
import (
"encoding/base64"
"fmt"
)
func main() {
rawString := "Telekit Tools ๐"
rawBytes := []byte(rawString)
// Standard Base64
stdEncoded := base64.StdEncoding.EncodeToString(rawBytes)
fmt.Println("Standard Base64:", stdEncoded)
// URL-Safe Base64 without padding (RFC 4648)
urlEncoded := base64.RawURLEncoding.EncodeToString(rawBytes)
fmt.Println("Base64URL:", urlEncoded)
// Decoding
decodedBytes, err := base64.StdEncoding.DecodeString(stdEncoded)
if err == nil {
fmt.Println("Decoded:", string(decodedBytes))
}
}4. Bash & Shell CLI (base64 Command)
# Encode string in Linux / macOS
echo -n "Telekit Tools" | base64
# Decode Base64 string
echo -n "VGVsZWtpdCBUb29scw==" | base64 --decode
# Encode an entire file without line wraps
base64 -w 0 icon.png > icon.b645. Rust (base64 Crate)
use base64::prelude::*;
fn main() {
let input = b"Telekit Tools รฐยยย";
let encoded = BASE64_STANDARD.encode(input);
println!("Base64: {}", encoded);
let decoded = BASE64_STANDARD.decode(&encoded).unwrap();
println!("Decoded: {}", String::from_utf8(decoded).unwrap());
}6. Java (java.util.Base64)
import java.util.Base64;
import java.nio.charset.StandardCharsets;
public class Base64Demo {
public static void main(String[] args) {
String original = "Telekit Tools ๐";
String encoded = Base64.getEncoder().encodeToString(original.getBytes(StandardCharsets.UTF_8));
System.out.println("Base64: " + encoded);
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
System.out.println("Decoded: " + decoded);
}
}7. PHP (base64_encode & base64_decode)
<?php
$original = "Telekit Tools ๐";
$encoded = base64_encode($original);
echo "Base64: " . $encoded . PHP_EOL;
$decoded = base64_decode($encoded);
echo "Decoded: " . $decoded . PHP_EOL;
?>8. C & OpenSSL (BIO_f_base64)
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <string.h>
#include <stdio.h>
void encode_base64(const char *message) {
BIO *bio, *b64;
b64 = BIO_new(BIO_f_base64());
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
bio = BIO_new_fp(stdout, BIO_NOCLOSE);
bio = BIO_push(b64, bio);
BIO_write(bio, message, strlen(message));
BIO_flush(bio);
BIO_free_all(bio);
printf("\n");
}Common Base64 Pitfalls & How to Avoid Them
When working with Base64 encoding across web stacks, keep these critical pitfalls in mind:
- Pitfall 1: Assuming Base64 is Encryption: Base64 is merely a transport format with zero confidentiality. Anyone can decode it in milliseconds. Never store passwords or secrets in Base64 without encrypting them with AES or hashing them with Bcrypt.
- **Pitfall 2:
btoa()Range Exceptions on Unicode**: Browserwindow.btoa()throws anInvalidCharacterErrorwhen encountering characters outside the Latin-1 (0โ255) range (such as emojis or non-English scripts). Always pass UTF-8 strings throughTextEncoderfirst. - Pitfall 3: URL Parameter Collision: Using standard Base64 in URL queries causes
+to be decoded into space characters, breaking token parsing. Always use RFC 4648 ยง5 Base64URL for query parameters and JSON Web Tokens. - Pitfall 4: Database Storage Overhead: Storing large files as Base64 strings in SQL text columns wastes 33% more disk space and increases memory pressure. Store raw binary data in native
BLOBorBYTEAcolumns instead.
Security & Privacy: Why Client-Side Execution Matters
Many online encoding websites transmit your text, tokens, or files to external backend servers. If you are encoding database connection strings, JWT authorization payloads, or private customer records, server-side processing introduces major compliance and data leak risks.
Telekit Tools performs all Base64 conversions 100% locally in your web browser using native JavaScript TypedArrays and Web APIs: - ๐ Zero Server Uploads: Your raw data never traverses the network or gets logged in access logs - โก Instant Microsecond Performance: No server round-trip latency or cloud queue delays - ๐ Full Offline Capability: Works reliably without an active internet connection - ๐ก๏ธ GDPR & Enterprise Safe: Ideal for internal tokens, API keys, and sensitive developer payloads
How to Encode and Decode Base64 Online (Step-by-Step)
Follow this quick-start base64 encoding guide to convert any text or file in seconds using the free Telekit encoder:
Step 1: Open the Base64 Encoder Tool Navigate to the free **Base64 Encoder/Decoder** โ no signup or installation required.
Step 2: Paste Your Text or Upload a File Type or paste any UTF-8 string, JSON payload, or upload binary content into the input field. The tool auto-detects the content type.
Step 3: Choose Standard Base64 or Base64URL Toggle between Standard Base64 and URL-Safe Base64URL (RFC 4648 ยง5). For image conversion, use the **Base64 Image Converter** to produce formatted Data URI strings directly.
Step 4: Toggle Encode or Decode Mode Select Encode (plaintext โ Base64) or Decode (Base64 โ plaintext). Use shortcut Alt+W to swap input and output fields.
Step 5: Copy the Result or Download Click Copy to copy the encoded/decoded string to your clipboard. All processing happens locally in your browser with zero server uploads.
Step 6: Validate Your Output Across Developer Tools For Base64-encoded JWT payloads, paste the token into the **JWT Decoder to inspect header and claims. For URL-encoded strings, use the URL Encoder/Decoder to handle percent-encoding. To evaluate storage efficiency against hex strings, view the Base64 vs Hex Comparison**.
Related Developer Tools
Enhance your data encoding and transformation workflow with these client-side utilities: - **Base64 Encoder/Decoder: Encode and decode UTF-8 text strings offline with real-time feedback - Base64 Image Converter: Convert PNG, JPG, and WebP images to Data URIs - Base64 vs Hex Encoding Comparison: Explore key differences, overhead calculations, and architectural tradeoffs between Base64 and Hex - UUID vs ULID vs NanoID Guide: Compare Crockford Base32 and Base64URL string encodings for unique identifiers - URL Encoder/Decoder: Escape query strings and RFC 3986 URI components - JWT Decoder: Inspect and decode JSON Web Token headers and claims safely - Understanding JWT Tokens Guide: Deep dive into RFC 7519 token anatomy, Base64URL claims decoding, and cryptographic signature verification - Binary Hex Converter: Convert between binary, hexadecimal, and decimal strings - Text to ASCII Converter: Convert text to decimal ASCII codes and binary byte streams - JSON Formatter**: Format and validate JSON before Base64-encoding it for API transmission