utf16

Standard UTF-16 (big-endian)

Created by: hackvertor
Installed 1 times

Category: Charsets

Created on: Monday, May 19, 2025 at 12:01:48 PM

Updated on: Wednesday, May 28, 2025 at 11:54:51 AM

This is a built in tag
Tag arguments
[]
Code
class utf16 {
  encode(input) {
    const buf = new ArrayBuffer(input.length * 2);
    const view = new DataView(buf);
    for (let i = 0; i < input.length; i++) {
      view.setUint16(i * 2, input.charCodeAt(i), false);
    }
    return Array.from(new Uint8Array(buf), (b) => String.fromCharCode(b)).join(
      "",
    );
  }

  decode(input) {
    const bytes = new Uint8Array(Array.from(input, (c) => c.charCodeAt(0)));
    const view = new DataView(bytes.buffer);
    let result = "";
    for (let i = 0; i < bytes.length; i += 2) {
      result += String.fromCharCode(view.getUint16(i, false));
    }
    return result;
  }
}