A practical guide to Base64: bits, padding and validation

Follow bytes through six-bit groups, calculate output size, and distinguish canonical Base64 from recoverable formatting issues.

Base64 is a representation of bytes using a restricted text alphabet. It is useful when a transport accepts text but the payload is binary. The operation is reversible: a correct decoder recovers the original bytes, including zeros and values that are not valid characters. Choosing how to interpret those bytes is a separate step.

Three bytes become four characters

A byte contains eight bits. Three bytes supply 24 bits, which split evenly into four groups of six. Each group selects one of 64 alphabet characters. The standard alphabet contains uppercase letters, lowercase letters, digits, plus and slash. For the ASCII text Man, the bytes are 4d 61 6e in hexadecimal, and the encoded output is TWFu.

Input bytes:  01001101 01100001 01101110
Six-bit sets: 010011 010110 000101 101110
Indexes:      19     22     5      46
Output:       T      W      F      u

Padding describes the final group

When one byte remains, the output has two alphabet characters and two equals signs. Two remaining bytes produce three alphabet characters and one equals sign. Thus M becomes TQ==, while Ma becomes TWE=. Padding is structural; adding random equals signs cannot recover a missing payload character. The unused bits in the final alphabet character must also be zero for canonical encoding.

For n input bytes, padded output has 4 × ceil(n / 3) characters. A 1,024-byte file therefore becomes 1,368 characters before a Data URI prefix or line wrapping is added. Base64 is not compression, although a separate transport compression layer may reduce the final transfer size.

Validate before interpreting

Use strict mode when testing a producer against a defined protocol. Use compatibility mode when a known source has inserted ASCII line breaks, omitted padding, or included a Data URI wrapper. Review the recorded adjustments. Unexpected punctuation, mixed alphabets and nonzero unused bits deserve investigation, not silent deletion.

Finally, inspect the decoded bytes. Valid Base64 can contain an invalid UTF-8 sequence, a truncated image, or an incomplete PDF. A successful decode proves only the encoding layer. Save binary results as bytes and use the appropriate file parser to check their structure. The alphabet, padding and canonical-bit rules are specified in RFC 4648.