Decoding Algorithm

Learn how decoders reconstruct original bytes, handle padding, and validate Base64 streams.

Interactive Tool: Practice in real-time with Pixlint's free browser-based Base64 Decoder. No data is uploaded.
Open tool →

Decoding reverses the encoding process: it reads Base64 characters in groups of 4, maps each character back to its 6-bit numeric value (0–63), packs them into a 24-bit integer, and extracts the original 8-bit bytes.

Step-by-Step Decoding Process

  1. Sanitize Input: Strip whitespace, newlines (\r\n), and optional data URI prefixes like data:*/*;base64,.
  2. Validate Character Set: Verify that every character belongs to the Base64 alphabet (A–Z, a–z, 0–9, +, /, or URL-safe equivalents -, _). Reject or flag unexpected characters.
  3. Process in 4-Character Blocks:
    • Convert character 1 → 6 bits
    • Convert character 2 → 6 bits
    • Convert character 3 → 6 bits (or detect = padding)
    • Convert character 4 → 6 bits (or detect = padding)
  4. Extract Bytes:
    triple = (val1 << 18) | (val2 << 12) | (val3 << 6) | val4
    byte1 = (triple >> 16) & 0xFF
    byte2 = (triple >> 8) & 0xFF
    byte3 = triple & 0xFF
  5. Handle Trailing Padding:
    • If the block ends with ==, output only byte1.
    • If the block ends with =, output byte1 and byte2.
    • If unpadded, output all 3 bytes.

Error Handling in Modern Decoders

Robust decoders must handle edge cases gracefully:

  • Mismatched Padding: Some systems omit trailing = padding (e.g. JWTs). Standard-compliant decoders can infer the missing padding from length % 4.
  • Non-zero Padding Bits: If the unused bits in the final byte are not zero, RFC 4648 specifies that strict decoders should report a validation warning or error to prevent data smuggling.