Return to Snippet

Revision: 25811
at April 10, 2010 15:08 by aadsm


Initial Code
function readUTF16String(bytes, bigEndian) {
    var ix = 0;
    var offset1 = 1, offset2 = 0;
    if( bytes.slice(0,2) == "\xFE\xFF") {
        bigEndian = true;
        ix = 2;
    } else if( bytes.slice(0,2) == "\xFF\xFE") {
        bigEndian = false;
        ix = 2;
    }
    
    if( bigEndian ) {
        offset1 = 0;
        offset2 = 1;
    }
    
    var string = "";
    for( ; ix < bytes.length; ix+=2 ) {
        var byte1 = bytes[ix+offset1].charCodeAt(0);
        var byte2 = bytes[ix+offset2].charCodeAt(0);
        var word1 = (byte1<<8)+byte2;
        if( byte1 < 0xD8 || byte1 >= 0xE0 ) {
            string += String.fromCharCode(word1);
        } else {
            ix+=2;
            var byte3 = bytes[ix+offset1].charCodeAt(0);
            var byte4 = bytes[ix+offset2].charCodeAt(0);
            var word2 = (byte3<<8)+byte4;
            string += String.fromCharCode(word1, word2);
        }
    }
    
    return string;
}

Initial URL

                                

Initial Description
This is useful if you have a string where each character represents a byte like the one returned by getStringAt() in BinaryAjax.

Initial Title
Read a UTF16 String from a "byte" source

Initial Tags

                                

Initial Language
JavaScript