DevFlow logoDevFlow
Encoding
~6 min read
All Glossary Terms

Base64 Encoding

Base64 is a binary-to-text encoding algorithm that converts binary data into an ASCII string using 64 printable characters as defined in RFC 4648.

Also known as:Base64Base64 EncodingBase64URLRFC 4648Radix-64Binary-to-Text

Base64 is a binary-to-text encoding scheme defined in RFC 4648 that translates arbitrary binary octets into a sequence of 64 printable ASCII characters. It is engineered to transmit binary data—such as image files, cryptographic signatures, or binary blobs—across legacy text-based transmission protocols like SMTP email, HTTP headers, XML, and JSON without risking data corruption or character set mangling.

You can encode and decode text or binary data directly in your browser using our Base64 Encoder & Decoder tool.


Technical Specifications at a Glance

Property Standard Base64 Base64URL (URL-Safe)
Standard Reference RFC 4648 §4 RFC 4648 §5
Alphabet Length 64 characters + padding (=) 64 characters (often unpadded)
Index 62 Character + (Plus sign) - (Minus / hyphen)
Index 63 Character / (Slash) _ (Underscore)
Padding Character = (Required for 3-byte alignment) Omitted or %3D
Safe for URL / Filenames? No (+ and / collide with URL delimiters) Yes (No percent-encoding required)
Payload Expansion +33.33% ($4 \text{ bytes per } 3 \text{ bytes}$) +33.33% ($4 \text{ bytes per } 3 \text{ bytes}$)

How Base64 Encoding Works Under the Hood

The Base64 algorithm maps binary data by grouping bits into 6-bit chunks (called sextets). Since $2^6 = 64$, each 6-bit chunk maps directly to one of 64 pre-defined ASCII characters:

Alphabet Index:
0–25:  A–Z
26–51: a–z
52–61: 0–9
62:    + (or - in Base64URL)
63:    / (or _ in Base64URL)

The 24-Bit Translation Process

  1. Divide Input into 3-Byte Blocks: Every 3 bytes of raw binary data equals 24 bits ($3 \times 8 = 24$).
  2. Split into 4 Sextets: The 24 bits are split into four 6-bit integers ($24 \div 6 = 4$).
  3. Lookup Characters: Each 6-bit integer (ranging from 0 to 63) is substituted by its corresponding character from the Base64 alphabet.
  4. Append Padding:
    • If the input length is divisible by 3, no padding is needed.
    • If 1 trailing byte remains ($8 \text{ bits}$), it is padded with four zero-bits to form two 6-bit characters, followed by two padding characters (==).
    • If 2 trailing bytes remain ($16 \text{ bits}$), they are padded with two zero-bits to form three 6-bit characters, followed by one padding character (=).
Plaintext:  "Man"
ASCII:      'M' (77)          'a' (97)          'n' (110)
Binary:     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 Split: [010011]   [010110]   [000101]   [101110]
Decimal:       19         22          5          46
Base64:        'T'        'W'        'F'        'u'   => "TWFu"

Base64 vs Base64URL

Standard Base64 contains two characters that present severe integration hurdles on the web:

  • The plus sign (+) is interpreted by query string parsers as an encoded space character.
  • The forward slash (/) is the universal path separator for file systems and URL routing.

To solve this, Base64URL (RFC 4648 §5) swaps + for - and / for _, and typically strips the trailing padding = characters. Base64URL is the foundation for modern web specifications, including JSON Web Tokens (JWT), OAuth 2.0 PKCE code verifiers, and WebAuthn credentials.


Code Examples: Encoding & Decoding

Modern JavaScript (Node.js and Browser)

// Safe UTF-8 Base64 Encoding in modern JavaScript/TypeScript
export function utf8ToBase64(text: string): string {
  const bytes = new TextEncoder().encode(text);
  const binString = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('');
  return btoa(binString);
}

// Convert Standard Base64 to URL-Safe Base64 (Base64URL)
export function toBase64Url(base64: string): string {
  return base64
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

// Decode Base64 back to UTF-8 string
export function base64ToUtf8(base64: string): string {
  const standard = base64.replace(/-/g, '+').replace(/_/g, '/');
  const binString = atob(standard);
  const bytes = Uint8Array.from(binString, (m) => m.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

Python 3

import base64

# Standard Base64
raw_bytes = b"Hello, World!"
encoded = base64.b64encode(raw_bytes).decode("ascii")  # "SGVsbG8sIFdvcmxkIQ=="
decoded = base64.b64decode(encoded)

# Base64URL (URL-Safe)
url_safe = base64.urlsafe_b64encode(raw_bytes).decode("ascii")

Pitfalls & Best Practices

  1. Base64 is NOT Encryption: Base64 provides zero confidentiality or security. Anyone who intercepts a Base64 string can instantly decode it with standard utilities. Never use Base64 to conceal secrets, tokens, or personal identifiable information (PII) without prior cryptographic encryption (e.g., using AES).
  2. Beware the 33% Network Bandwidth Penalty: Encoding images or binaries in Base64 increases the raw payload size by 33.3% (plus gzip/brotli inefficiency). For HTTP APIs and web performance, serve binary assets through standard media URLs with caching headers rather than inlining gigantic Base64 strings into HTML or CSS.
  3. Handle Unicode & Multi-byte UTF-8 Properly: In JavaScript, passing strings containing emojis, accents, or Asian characters directly into window.btoa() throws a DOMException: The string to be encoded contains characters outside of the Latin1 range. Always encode text to a UTF-8 byte array using TextEncoder first.

Frequently Asked Questions

Is Base64 a form of encryption or compression?

No. Base64 is neither encryption nor compression. It is an encoding format designed for data interchange. It provides no secrecy (it can be decoded by anyone) and actually increases file size by approximately 33%, the opposite of compression.

Why does Base64 sometimes end with one or two = characters?

The equal sign (=) is a padding character. Because Base64 processes data in 3-byte (24-bit) chunks, inputs whose lengths are not cleanly divisible by 3 require padding. One = signifies that 2 bytes were encoded; two == signify that only 1 byte was encoded.

Why use Base64URL instead of standard Base64?

Standard Base64 contains + and /, which interfere with URL paths and query parameters. For example, web servers often parse + as a space, corrupting the payload. Base64URL replaces + with - and / with _, allowing safe transmission in URLs, cookies, and HTTP headers without needing secondary URL Encoding.

Can all binary files be converted to Base64?

Yes. Any arbitrary file format—including PNG, JPEG, PDF, WASM binaries, and cryptographic keys—consists of binary bytes that can be converted to Base64 and reconstructed with zero data loss. Try it yourself with our client-side Base64 Tool.

Interactive Tools for Base64 Encoding

Free, browser-based utilities to test, generate, and inspect Base64 Encoding payloads directly.

100% Client-Side • No Telemetry