Skip to content

Instantly share code, notes, and snippets.

@also
Created April 10, 2011 22:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save also/912792 to your computer and use it in GitHub Desktop.
Save also/912792 to your computer and use it in GitHub Desktop.
Decode JavaScript UTF-16 arrays
// http://www.ietf.org/rfc/rfc2781.txt
function decodeUtf16(w) {
var i = 0;
var len = w.length;
var w1, w2;
var charCodes = [];
while (i < len) {
var w1 = w[i++];
if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
charCodes.push(w1);
continue;
}
if ((w1 & 0xFC00) === 0xD800) { // w1 >= 0xD800 && w1 <= 0xDBFF
throw new RangeError('Invalid octet 0x' + w1.toString(16) + ' at offset ' + (i - 1));
}
if (i === len) {
throw new RangeError('Expected additional octet');
}
w2 = w[i++];
if ((w2 & 0xFC00) !== 0xDC00) { // w2 < 0xDC00 || w2 > 0xDFFF)
throw new RangeError('Invalid octet 0x' + w2.toString(16) + ' at offset ' + (i - 1));
}
charCodes.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
}
return String.fromCharCode.apply(String, charCodes);
}
@Vau8422
Copy link

Vau8422 commented Feb 9, 2018

encode Utf16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment