Skip to content

Instantly share code, notes, and snippets.

@surma
Created March 23, 2022 11:16
Show Gist options
  • Save surma/f45197f183bcdc4555812d94f3e0cf27 to your computer and use it in GitHub Desktop.
Save surma/f45197f183bcdc4555812d94f3e0cf27 to your computer and use it in GitHub Desktop.
const LOOKUP =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
export function encodeBase64(buffer) {
const view = new Uint8Array(buffer);
let out = [];
for (let i = 0; i < view.length; i += 3) {
const [b1, b2 = 0x10000, b3 = 0x10000] = view.subarray(i, i + 3);
out.push(
b1 >> 2,
((b1 << 4) | (b2 >> 4)) & 63,
b2 <= 0xff ? ((b2 << 2) | (b3 >> 6)) & 63 : 64,
b3 <= 0xff ? b3 & 63 : 64
);
}
return out.map((c) => LOOKUP[c]).join("");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment