Skip to content

Instantly share code, notes, and snippets.

@vladignatyev
Last active November 9, 2021 09:42
Show Gist options
  • Save vladignatyev/b9792c861f28f75244cfc66769569591 to your computer and use it in GitHub Desktop.
Save vladignatyev/b9792c861f28f75244cfc66769569591 to your computer and use it in GitHub Desktop.
toBinary() and fromBinary() workaround to make atob() and btoa() work with UTF strings. Example for the original blog post at https://base64tool.com website
/*
* The following snippet is from the Mozilla Developer Portal documentation.
* Utility functions toBinary() and fromBinary() make possible to use btoa() and atob()
* with UTF strings.
*
* The original example here: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/btoa
* For additional information see: https://base64tool.com/uncaught-domexception-btoa-on-window/
*
* Usage example:
* > btoa(toBinary('☸☹☺☻☼☾☿'))
* OCY5JjomOyY8Jj4mPyY=
* > fromBinary(atob('OCY5JjomOyY8Jj4mPyY='))
* ☸☹☺☻☼☾☿
**/
// convert a Unicode string to a string in which
// each 16-bit unit occupies only one byte
function toBinary(string) {
const codeUnits = new Uint16Array(string.length);
for (let i = 0; i < codeUnits.length; i++) {
codeUnits[i] = string.charCodeAt(i);
}
return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
}
// convert a binary string back into a normal Javascript string
function fromBinary(binary) {
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return String.fromCharCode(...new Uint16Array(bytes.buffer));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment