Created
April 10, 2011 22:17
-
-
Save also/912792 to your computer and use it in GitHub Desktop.
Decode JavaScript UTF-16 arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
encode Utf16