Skip to content

Instantly share code, notes, and snippets.

@gera2ld
Last active September 7, 2023 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gera2ld/3c56cca09745cb113d86b621621d1d68 to your computer and use it in GitHub Desktop.
Save gera2ld/3c56cca09745cb113d86b621621d1d68 to your computer and use it in GitHub Desktop.
Base64 encoder / decoder with unicode support
// See https://github.com/gera2ld/js-lib
const CHUNK_SIZE = 8192;
function bytes2string(bytes) {
const chunks = [];
for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {
chunks.push(String.fromCharCode(...bytes.slice(i, i + CHUNK_SIZE)));
}
return chunks.join('');
}
function utf8decode(binary) {
const bytes = [];
let i = 0;
let c1 = 0;
let c2 = 0;
let c3 = 0;
while (i < binary.length) {
c1 = binary.charCodeAt(i);
if (c1 < 128) {
bytes.push(c1);
i += 1;
} else if (c1 > 191 && c1 < 224) {
c2 = binary.charCodeAt(i + 1);
// eslint-disable-next-line no-bitwise
bytes.push(((c1 & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = binary.charCodeAt(i + 1);
c3 = binary.charCodeAt(i + 2);
// eslint-disable-next-line no-bitwise
bytes.push(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return bytes2string(bytes);
}
/* eslint-disable no-bitwise */
function utf8encode(string) {
const bytes = [];
for (let i = 0; i < string.length; i += 1) {
const code = string.charCodeAt(i);
if (code < 128) {
bytes.push(code);
} else if (code < 2048) {
bytes.push(
(code >> 6) | 192,
(code & 63) | 128,
);
} else {
bytes.push(
(code >> 12) | 224,
((code >> 6) & 63) | 128,
(code & 63) | 128,
);
}
}
return bytes2string(bytes);
}
function base64decode(base64) {
return utf8decode(atob(base64));
}
function base64encode(text) {
return btoa(utf8encode(text));
}
function base64encode(text) {
return Buffer.from(text).toString('base64');
}
function base64decode(base64) {
return Buffer.from(base64, 'base64').toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment