Created
May 29, 2023 15:58
-
-
Save rfl890/e3c01d6285573f00cb333f6141c4f071 to your computer and use it in GitHub Desktop.
btoa and atob with UTF-8 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
function btoaUTF8(data) { | |
const utf8Data = new TextEncoder().encode(data); | |
let binaryString = ""; | |
for (let i = 0; i < utf8Data.length; i++) { | |
binaryString += String.fromCharCode(utf8Data[i]); | |
} | |
return btoa(binaryString); | |
} | |
function atobUTF8(data) { | |
const decodedData = atob(data); | |
const utf8data = new Uint8Array(decodedData.length); | |
const decoder = new TextDecoder("utf-8"); | |
for (let i = 0; i < decodedData.length; i++) { | |
utf8data[i] = decodedData.charCodeAt(i); | |
} | |
return decoder.decode(utf8data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment