JS: Char to UTF-16 Encoding 🚀

By Xah Lee. Date: .

Here is a function to convert character to its UTF-16 Encoding.

/*
xah_codepoint_to_utf16_hexStr(cp) return a string of hexadecimal that's the UTF-16 encoding of the char of codepoint cp (integer).
The result string is not padded, but one space is inserted to separate the first 2 bytes and last 2 bytes. Digits are in CAPITAL case.

URL http://xahlee.info/js/js_utf-16_encoding.html
version 2022-10-17
*/
const xah_codepoint_to_utf16_hexStr = ((cp) => {
  const xCharStr = String.fromCodePoint(cp);
  if (cp < 2 ** 16) {
    return xCharStr.charCodeAt(0).toString(16).toUpperCase();
  } else {
    const xLen = String.fromCodePoint(cp).length;
    const xout = [];
    for (let i = 0; i < xLen; i++) {
      xout.push(xCharStr.charCodeAt(i).toString(16).toUpperCase());
    }
    return xout.join(" ");
  }
});

// ssss---------------------------------------------------
// test

/*
character: 😂
codepoint 128514
hexadecimal 1f602
utf-8: F0 9F 98 82
utf-16: D8 3D DE 02
*/

console.log(xah_codepoint_to_utf16_hexStr(128514) === "D83D DE02");

const xah_random_int =
  ((xmin, xmax) => (Math.floor(Math.random() * (xmax + 1 - xmin) + xmin)));

for (let i = 0; i < 30; i++) {
  console.log(xah_codepoint_to_utf16_hexStr(xah_random_int(100, 300000)));
}

JavaScript, String, Char, Encoding, Hexadecimal

BUY ΣJS JavaScript in Depth