Belajar
← All lessons

How base64 works

3 bytes in, 4 characters out

base64.js

const ABC = "ABC…XYZabc…xyz0123456789+/"; function base64(bytes) {  let out = "";  for (let i = 0; i < bytes.length; i += 3) {    // take 3 bytes, 24 bits    const n = bytes[i] << 16      | (bytes[i + 1] ?? 0) << 8      | (bytes[i + 2] ?? 0);    // cut into four 6-bit numbers    const six = [n >> 18, n >> 12, n >> 6, n]      .map((v) => ABC[v & 63]);    // short last group: pad with =    const left = bytes.length - i;    if (left === 1) six[2] = six[3] = "=";    if (left === 2) six[3] = "=";    out += six.join("");  }  return out;}

Encode your own text group by group

TextAlphabetbase64base64url
3-byte groups
Output

0bytes in
0chars out
-bigger

base64.js

const ABC = "ABC…XYZabc…xyz0123456789+/"; function base64(bytes) {  let out = "";  for (let i = 0; i < bytes.length; i += 3) {    // take 3 bytes, 24 bits    const n = bytes[i] << 16      | (bytes[i + 1] ?? 0) << 8      | (bytes[i + 2] ?? 0);    // cut into four 6-bit numbers    const six = [n >> 18, n >> 12, n >> 6, n]      .map((v) => ABC[v & 63]);    // short last group: pad with =    const left = bytes.length - i;    if (left === 1) six[2] = six[3] = "=";    if (left === 2) six[3] = "=";    out += six.join("");  }  return out;}

base64url.js

// swap the two characters URLs treat speciallyconst b64url = base64(bytes)  .replace(/\+/g, "-")  .replace(/\//g, "_")  .replace(/=+$/, ""); // or let the runtime do itbtoa(binaryString);Buffer.from(bytes).toString("base64url");

Topics

Next: How embedded systems work

Open lesson