Skip to content

Instantly share code, notes, and snippets.

@MonksterFX
Last active May 19, 2022 18:54
Show Gist options
  • Save MonksterFX/dbece5c56205640d6163ab27e298d342 to your computer and use it in GitHub Desktop.
Save MonksterFX/dbece5c56205640d6163ab27e298d342 to your computer and use it in GitHub Desktop.
Encode UTF-8 String To Base64 In Browser
// More Information on Base64
// http://www.sunshine2k.de/articles/coding/base64/understanding_base64.html
// https://gist.github.com/Nijikokun/5192472
// https://developer.mozilla.org/en-US/docs/Glossary/Base64#solution_2_%E2%80%93_rewriting_atob_and_btoa_using_typedarrays_and_utf-8
// convert string to UInt8Array
const enc = new TextEncoder().encode('ääüß');
// calculate filling bytes
const emtpy = enc.length % 3 > 0 ? 3 - (enc.length % 3) : 0;
// concat UInt8Array and filling bytes
const bytes = [...enc, ...new Array(emtpy).fill(NaN)];
// mapping number to char
const map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let b64 = [];
// iterate trough UInt8Array in tuples of three
for (let i = 0; i < bytes.length; i = i + 3) {
b64.push(bytes[0 + i] >> 2);
b64.push(((bytes[0 + i] & 0b11) << 4) | (bytes[1 + i] >> 4));
b64.push(((bytes[1 + i] & 0b1111) << 2) | (bytes[2 + i] >> 6));
b64.push(bytes[2 + i] & 0b111111);
}
// check if '=' must be applied on the last two positions
b64[b64.length - 2] = isNaN(bytes[bytes.length - 2]) ? 64 : b64[b64.length - 2];
b64[b64.length - 1] = isNaN(bytes[bytes.length - 1]) ? 64 : b64[b64.length - 1];
// translate encoded values
const result = b64.reduce((p, c) => p + map.charAt(c), '');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment