Last active
September 7, 2023 14:39
-
-
Save gera2ld/3c56cca09745cb113d86b621621d1d68 to your computer and use it in GitHub Desktop.
Base64 encoder / decoder with unicode support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// See https://github.com/gera2ld/js-lib |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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