utf16LE

utf16LE – UTF-16 Little Endian

Created by: hackvertor
Installed 1 times

Category: Charsets

Created on: Monday, May 19, 2025 at 12:03:50 PM

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

This is a built in tag
Tag arguments
[]
Code
class utf16LE {
  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), true);
    }
    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, true));
    }
    return result;
  }
}