Understanding base64 encoding
Some channels only accept plain text, yet the data travelling through them is not always text. An email attachment is a picture, a token inside a web address may carry binary bytes, and an interface that expects letters and digits will choke on a raw byte it cannot print. Base64 solves that mismatch by re-expressing any bytes as ordinary letters, digits and two extra symbols, so the result survives copying, pasting and transmission through systems that only handle text.
Formula and method
Encoding: Text — the characters entered, read as UTF-8 bytes before encoding. A plain English letter is one byte; characters from other scripts may take two, three or four bytes each. Groups of three bytes — the input bytes are taken three at a time. Each group of three bytes (24 bits) is split into four groups of six bits. Six-bit values — each six-bit group picks one character from the 64-character alphabet: A–Z for values 0–25, a–z for 26–51, 0–9 for 52–61, plus for 62 and slash for 63. Padding — when the final group has only one byte, two equals signs are added; when it has two bytes, one equals sign is added. A complete group of three bytes needs no padding. Why three bytes become four characters. Three bytes hold 24 bits, and 24 divides neatly into four chunks of six bits, so nothing is wasted and nothing is left over. Why the result grows by about a third. Four characters carry the information of three bytes, so the output is four-thirds as long as the input — an eleven-byte phrase becomes sixteen characters, and a six-byte word becomes eight. Why decoding needs valid input. Decoding reverses the mapping, so the string must use only the 64 alphabet characters plus padding at the end, and the bytes it produces must form valid UTF-8 text. A string with a stray character, padding in the wrong place or bytes that are not valid UTF-8 cannot be decoded into text. Why this is not security. The alphabet and the grouping are public and fixed, so decoding needs no key and no secret. Encoding hides nothing from anyone who bothers to look.
Worked example
Example 1 — "Hello world" encoded (the live-page example) The text "Hello world" with the action Encode. Input bytes: "Hello world" is 11 bytes (ten letters plus one space, one byte each) Groups: 11 bytes form three full groups of three, leaving a final group of two bytes Encoded output: SGVsbG8gd29ybGQ= Padding: one = sign, because the final group holds two bytes rather than three Result: SGVsbG8gd29ybGQ= (converted text) That matches the example stored on the live page, worked through step by step above. Eleven bytes become sixteen characters: twelve characters for the three full groups, plus four characters for the final two bytes, one of which is padding. Decoding SGVsbG8gd29ybGQ= returns "Hello world" exactly, space included.