How Base64 Converts 3 Bytes to 4 ASCII Characters
Base64 encoding is a binary-to-text translation process designed to represent arbitrary binary data in a human-readable and network-safe ASCII format. It operates on a fundamental mathematical alignment: taking 24 bits of input data—equivalent to three standard 8-bit bytes—and regrouping them into four 6-bit units. Each 6-bit unit corresponds to a decimal value from 0 to 63, which directly indexes a standardized 64-character lookup table to output four printable ASCII characters.
The Mathematics of the 24-Bit Block
Standard computing architectures store data in 8-bit bytes, where each byte can hold \(2^8\) (256) possible values. However, many legacy transmission protocols only safely handle printable 7-bit ASCII characters.
Base64 solves this by finding the least common multiple between the 8-bit byte system and a safe 6-bit representation: * Three 8-bit bytes equal 24 total bits (\(3 \times 8 = 24\)). * Four 6-bit segments equal 24 total bits (\(4 \times 6 = 24\)).
Because \(2^6 = 64\), every 6-bit sequence has a numerical range from 000000 (0) to 111111 (63).
The Base64 Index Table
Each integer from 0 to 63 maps to a specific printable ASCII
character: * 0–25: Uppercase letters A
through Z * 26–51: Lowercase letters
a through z * 52–61: Digits
0 through 9 * 62: Symbol
+ * 63: Symbol /
Step-by-Step Binary Transformation Example
Consider encoding the three-letter text string “Man”:
Convert to Binary: Each character is converted to its 8-bit ASCII binary value.
M= Decimal 77 =01001101a= Decimal 97 =01100001n= Decimal 110 =01101110
Concatenate the Bits: The three bytes merge into a single 24-bit stream:
010011010110000101101110Divide into Four 6-Bit Chunks: The 24-bit sequence is partitioned into four equal parts:
- Chunk 1:
010011 - Chunk 2:
010110 - Chunk 3:
000101 - Chunk 4:
101110
- Chunk 1:
Convert Chunks to Decimal:
010011= 16 + 2 + 1 = 19010110= 16 + 4 + 2 = 22000101= 4 + 1 = 5101110= 32 + 8 + 4 + 2 = 46
Map to Base64 Characters:
- Index 19 =
T - Index 22 =
W - Index 5 =
F - Index 46 =
u
- Index 19 =
The three input bytes "Man" output the four Base64
characters "TWFu".
Handling Incomplete 3-Byte Blocks (Padding)
When the input payload length is not divisible by 3, the data is
padded with zero bits to complete the final 6-bit chunk, and the equal
sign (=) is appended to fill the 4-character output block:
* 1 remaining byte (8 bits): Yields two 6-bit chunks
(using 4 trailing zero bits) followed by two = padding
characters (e.g., XX==). * 2 remaining bytes (16
bits): Yields three 6-bit chunks (using 2 trailing zero bits)
followed by one = padding character (e.g.,
XXX=).