From 037faf024ea29cb16dccd699461b0a07ed62e40b Mon Sep 17 00:00:00 2001 From: Mastermindzh Date: Thu, 23 Sep 2021 14:20:12 +0200 Subject: [PATCH] added utf-16-base64 example --- README.md | 3 +- javascript/encoding/utf-16-base64.js | 41 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 javascript/encoding/utf-16-base64.js diff --git a/README.md b/README.md index fcee0dd..62c55ad 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,8 @@ It also consolidates all relevant examples in 1 place │ ├── async.js │ ├── image.png │ └── README.md - +│ └── encoding +│ └── utf-16-base64.js # an example showing how to encode/decode UTF-16 strings ├── js-ts-frameworks # JS-TS framework specific examples │ ├── Angular │ │ └── state diff --git a/javascript/encoding/utf-16-base64.js b/javascript/encoding/utf-16-base64.js new file mode 100644 index 0000000..5e32898 --- /dev/null +++ b/javascript/encoding/utf-16-base64.js @@ -0,0 +1,41 @@ +/** + * Base 64 encodes UTF-16 encoded strings + * + * @param {*} string + * @return {*} + */ +function btoaUTF16(string) { + const charCodeArray = new Uint16Array(string.length); + + // you could use a for loop without the split to move in the string for better performance + string.split("").forEach((_, index) => { + charCodeArray[index] = string.charCodeAt(index); + }); + + return btoa(String.fromCharCode(...new Uint16Array(charCodeArray.buffer))); +} + +/** + * Decodes base64 encoded UTF-16 strings + * + * @param {*} encoded + * @return {*} + */ +function atobUTF16(encoded) { + binary = atob(encoded); + const bytes = new Uint16Array(binary.length); + + // you could use a for loop without the split to move in the string for better performance + binary.split("").forEach((_, index) => { + bytes[index] = binary.charCodeAt(index); + }); + + return String.fromCharCode(...new Uint16Array(bytes.buffer)); +} + +// Our base64 string with weird chars +const encoded = btoaUTF16("HUË - Sársziget"); +const decoded = atobUTF16(encoded); + +console.log("encoded:", encoded); +console.log("decoded:", decoded);