Base64 encode/decode · Guide

Base64 Encoding Algorithm: How 3 Bytes Become 4 Characters

Base64 has one idea behind it: regroup bits from 8 at a time into 6 at a time, so every group can be written as a character that survives any text channel. Everything else — the alphabet, the padding — follows from that.

Regrouping the bits

Take 3 bytes: 24 bits. Split those 24 bits into four groups of 6. Each 6-bit group is a number from 0 to 63, and each number maps to one character of the alphabet. So 3 bytes in, 4 characters out — the 4/3 ratio that makes output 33% larger.

Worked through with "Man": the bytes are 77, 97, 110, which as bits is 010011010110000101101110. Regrouped into sixes: 010011 010110 000101 101110 = 19, 22, 5, 46, which index to T, W, F, u — giving TWFu.

The alphabet

Indexes 0-25 are A-Z, 26-51 are a-z, 52-61 are 0-9, then 62 and 63. Those last two are the only place variants differ: standard Base64 uses + and /, base64url uses - and _ because the standard pair has meaning in URLs.

The 64 characters were chosen to be safe in every common encoding and protocol — no control characters, nothing that a mail gateway or a text field would mangle.

Padding

Input rarely divides evenly by 3. With 2 leftover bytes (16 bits) you get three characters and pad with one =; with 1 leftover byte (8 bits) you get two characters and pad with two =. Padding carries no data — it only signals how many bytes the final group represents.

That is why valid Base64 length is always a multiple of 4, and why = can only appear at the end. Padding in the middle of a string means two Base64 values were concatenated.

Decoding

Decoding reverses exactly: map each character back to its 6-bit value, concatenate, and split into 8-bit bytes, discarding the bits the padding accounts for. There is no ambiguity and no loss.

Decoders differ only in strictness — some reject whitespace and unknown characters, others skip them. That difference is worth knowing when a string decodes in one tool and fails in another.

Frequently asked questions

Why is Base64 exactly 33% larger?

Four output characters represent three input bytes, so the ratio is 4/3, plus up to two padding characters.

Can Base64 output contain "=" in the middle?

Not in a single valid value. Padding only appears at the end.

Is Base64 compression?

The opposite — it expands data. Compress first if size matters, then encode.

Ready to try it?

Open the free browser-based Base64 encode/decode and apply what you just read — no sign-up, runs locally.

Open the Base64 encode/decode tool